zoukankan      html  css  js  c++  java
  • Linux下的Json串解析

    1、安装 jsoncpp

     sudo apt-get install libjsoncpp-dev 

    2、位置

    头文件在:

    /usr/include/jsoncpp/json

    动态库在:

    /usr/lib/x86_64-linux-gnu/libjsoncpp.so.***

    3、使用

     1 #include <stdio.h>
     2 #include <string>
     3 #include <iostream>
     4 #include <jsoncpp/json/json.h>
     5 using namespace std;
     6 int main()
     7 {
     8 
     9     string strValue =  "{"array":[{"recipient_id":"1235","text":"好,请稍等,正在为您查询"},{"recipient_id":"1235","text":"结果为***"},{"recipient_id":"1235","text":"您还需要什么服务?"}]}";
    10     cout << "JsonString:" << strValue << endl;
    11     Json::Reader reader; 
    12     Json::Value root; 
    13     if (reader.parse(strValue, root))
    14     { 
    15         // if (!root["key"].isNull())
    16         // {
    17         //     std::string strValue= root["key"].asString(); 
    18         //     std::cout << strValue<< std::endl; 
    19         // }
    20         Json::Value arrayObj = root["array"]; 
    21         for (int i=0; i<arrayObj.size(); i++) 
    22         { 
    23             string id = arrayObj[i]["recipient_id"].asString(); 
    24             string str = arrayObj[i]["text"].asString(); 
    25             std::cout << "text:" << str << std::endl;  
    26             std::cout << "recipient_id:" << id << std::endl;  
    27         } 
    28     }
    29 
    30     string strValue1 =  "[{"recipient_id":"1235","text":"好,请稍等,正在为您查询"},{"recipient_id":"1235","text":"结果***"},{"recipient_id":"1235","text":"您还需要什么服务?"}]";
    31     Json::Value array;
    32 
    33     cout << "JsonString:" << strValue1 << endl;
    34 
    35     if (reader.parse(strValue1, array))
    36     { 
    37         for (int i=0; i<array.size(); i++) 
    38         { 
    39             string id = array[i]["recipient_id"].asString(); 
    40             string str = array[i]["text"].asString(); 
    41             string str1 = array[i]["text1"].asString(); 
    42             std::cout << "text1:" << str1 << std::endl;
    43             std::cout << "text:" << str << std::endl;  
    44             std::cout << "recipient_id:" << id << std::endl;  
    45         } 
    46     }
    47     return 0;
    48 }
    49 
    50 /*
    51 * 使用以下命令进行编译:
    52 * g++ -std=c++11 -o JsonTest JsonTest.cpp -ljsoncpp
    53 */

    4、运行结果

  • 相关阅读:
    Python-环境配置
    Linux操作系统基
    BZOJ 1572 贪心(priority_queue)
    POJ 3040 贪心
    POJ 3039 搜索??? (逼近)
    POJ 2433 枚举
    BZOJ 1571 DP
    BZOJ 1232 Kruskal
    BZOJ 1231 状压DP
    POJ 2430 状压DP
  • 原文地址:https://www.cnblogs.com/zhengguiping--9876/p/13571975.html
Copyright © 2011-2022 走看看