JsonCpp使用方法详解

转自:http://blog.csdn.net/u012372584/article/details/78901015

 

JSON全称为JavaScript ObjectNotation,它是一种轻量级的数据交换格式,易于阅读、编写、解析。jsoncpp是c++解析JSON串常用的解析库之一。

jsoncpp中主要的类:

Json::Value:可以表示所有支持的类型,如:int , double ,string , object, array等。其包含节点的类型判断(isNull,isBool,isInt,isArray,isMember,isValidIndex等),类型获取(type),类型转换(asInt,asString等),节点获取(get,[]),节点比较(重载<,<=,>,>=,==,!=),节点操作(compare,swap,removeMember,removeindex,append等)等函数。

Json::Reader:将文件流或字符串创解析到Json::Value中,主要使用parse函数。Json::Reader的构造函数还允许用户使用特性Features来自定义Json的严格等级。

Json::Writer:与JsonReader相反,将Json::Value转换成字符串流等,Writer类是一个纯虚类,并不能直接使用。在此我们使用 Json::Writer 的子类:Json::FastWriter(将数据写入一行,没有格式),Json::StyledWriter(按json格式化输出,易于阅读)。

Json::Reader可以通过对Json源目标进行解析,得到一个解析好了的Json::Value,通常字符串或者文件输入流可以作为源目标。


如下Json文件example.json:

 

[html] view plain copy
 
  1. {  
  2.     "encoding" : "UTF-8",  
  3.     "plug-ins" : [  
  4.         "python",  
  5.         "c++",  
  6.         "ruby"  
  7.         ],  
  8.     "indent" : { "length" : 3, "use_space": true }  
  9.     "tab":null  
  10. }  


使用Json::Reader对Json文件进行解析:

 

 

[html] view plain copy
 
  1. Json::Value root;  
  2. Json::Reader reader;  
  3. std::ifstream ifs("example.json");//open file example.json  
  4.   
  5. if(!reader.parse(ifs, root)){  
  6.    // fail to parse  
  7. }  
  8. else{  
  9.    // success  
  10.    std::cout<<root["encoding"].asString()<<endl;  
  11.    std::cout<<root["indent"]["length"].asInt()<<endl;  
  12. }  


使用Json::Reader对字符串进行解析:

 

 

[html] view plain copy
 
  1. Json::Value root;  
  2.   Json::Reader reader;  
  3.   const char* s = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";   
  4.   if(!reader.parse(s, root)){  
  5.     // "parse fail";  
  6.   }  
  7.   else{  
  8.       std::cout <root["uploadid"].asString();//print "UP000000"  
  9.   }  


Json::Writer 和 Json::Reader相反,是把Json::Value对象写到string对象中,而且Json::Writer是个抽象类,被两个子类Json::FastWriter和Json::StyledWriter继承。 
简单来说FastWriter就是无格式的写入,这样的Json看起来很乱没有格式,而StyledWriter就是带有格式的写入,看起来会比较友好。

 

 

[html] view plain copy
 
  1. Json::Value root;  
  2. Json::Reader reader;  
  3. Json::FastWriter fwriter;  
  4. Json::StyledWriter swriter;  
  5.   
  6. if(! reader.parse("example.json", root)){  
  7. // parse fail  
  8.     return 0;  
  9. }  
  10. std::string str = fwriter(root);  
  11. std::ofstream ofs("example_fast_writer.json");  
  12. ofs <str;  
  13. ofs.close();  
  14.   
  15. str = swriter(root);  
  16. ofs.open("example_styled_writer.json");  
  17. ofs <str;  
  18. ofs.close();  
  19.   
  20. 结果1:example_styled_writer.json:  
  21. {  
  22.     "encoding" : "UTF-8",  
  23.     "plug-ins" : [  
  24.         "python",  
  25.         "c++",  
  26.         "ruby"  
  27.         ],  
  28.     "indent" : { "length" : 3, "use_space": true }  
  29.     "tab":null  
  30. }  
  31.   
  32. 结果2:example_fast_writer.json:  
  33. {"encoding" : "UTF-8","plug-ins" : ["python","c++","ruby"],"indent" : { "length" : 3, "use_space": true}}  


Json其它函数的应用:
1、判断KEY值是否存在:

 

 

[html] view plain copy
 
  1. if(root.isMember("encoding")){  
  2.     std::cout<<"encoding is a member"<<std::endl;  
  3. }  
  4. else{  
  5.     std::cout<<"encoding is not a member"<<std::endl;  
  6. }  


2、判断Value是否为null:

 

if(root["tab"].isNull()){
    std::cout << "isNull" <<std::endl;//print isNull
}

 

完整例子使用举例来自于CSDN下载网友的程序:

源码下载地址:http://download.csdn.net/download/woniu211111/9966907

 

[html] view plain copy
 
  1. /********************************************************  
  2. Copyright (C), 2016-2017,  
  3. FileName:   main  
  4. Author:     woniu201  
  5. Email:      wangpengfei.201@163.com  
  6. Created:    2017/09/06  
  7. Description:use jsoncpp src , not use dll, but i also provide dll and lib.  
  8. ********************************************************/  
  9.   
  10. #include "stdio.h"  
  11. #include <string>  
  12. #include "jsoncpp/json.h"  
  13.   
  14. using namespace std;  
  15.   
  16. /************************************  
  17. @ Brief:        read file  
  18. @ Author:       woniu201   
  19. @ Created:      2017/09/06  
  20. @ Return:       file data    
  21. ************************************/  
  22. char *getfileAll(char *fname)  
  23. {  
  24.     FILE *fp;  
  25.     char *str;  
  26.     char txt[1000];  
  27.     int filesize;  
  28.     if ((fp=fopen(fname,"r"))==NULL){  
  29.         printf("open file %s fail \n",fname);  
  30.         return NULL;  
  31.     }  
  32.   
  33.     /*  
  34.     获取文件的大小  
  35.     ftell函数功能:得到流式文件的当前读写位置,其返回值是当前读写位置偏离文件头部的字节数.  
  36.     */  
  37.     fseek(fp,0,SEEK_END);   
  38.     filesize = ftell(fp);  
  39.   
  40.     str=(char *)malloc(filesize);  
  41.     str[0]=0;  
  42.   
  43.     rewind(fp);  
  44.     while((fgets(txt,1000,fp))!=NULL){  
  45.         strcat(str,txt);  
  46.     }  
  47.     fclose(fp);  
  48.     return str;  
  49. }  
  50.   
  51. /************************************  
  52. @ Brief:        write file  
  53. @ Author:       woniu201   
  54. @ Created:      2017/09/06  
  55. @ Return:             
  56. ************************************/  
  57. int writefileAll(char* fname,const char* data)  
  58. {  
  59.     FILE *fp;  
  60.     if ((fp=fopen(fname, "w")) == NULL)  
  61.     {  
  62.         printf("open file %s fail \n", fname);  
  63.         return 1;  
  64.     }  
  65.       
  66.     fprintf(fp, "%s", data);  
  67.     fclose(fp);  
  68.       
  69.     return 0;  
  70. }  
  71.   
  72. /************************************  
  73. @ Brief:        parse json data  
  74. @ Author:       woniu201   
  75. @ Created:      2017/09/06  
  76. @ Return:             
  77. ************************************/  
  78. int parseJSON(const char* jsonstr)  
  79. {  
  80.     Json::Reader reader;  
  81.     Json::Value  resp;  
  82.   
  83.     if (!reader.parse(jsonstr, resp, false))  
  84.     {  
  85.         printf("bad json format!\n");  
  86.         return 1;  
  87.     }  
  88.     int result = resp["Result"].asInt();  
  89.     string resultMessage = resp["ResultMessage"].asString();  
  90.     printf("Result=%d; ResultMessage=%s\n", result, resultMessage.c_str());  
  91.   
  92.     Json::Value & resultValue = resp["ResultValue"];  
  93.     for (int i=0; i<resultValue.size(); i++)  
  94.     {  
  95.         Json::Value subJson = resultValue[i];  
  96.         string cpuRatio = subJson["cpuRatio"].asString();  
  97.         string serverIp = subJson["serverIp"].asString();  
  98.         string conNum = subJson["conNum"].asString();  
  99.         string websocketPort = subJson["websocketPort"].asString();  
  100.         string mqttPort = subJson["mqttPort"].asString();  
  101.         string ts = subJson["TS"].asString();  
  102.   
  103.         printf("cpuRatio=%s; serverIp=%s; conNum=%s; websocketPort=%s; mqttPort=%s; ts=%s\n",cpuRatio.c_str(), serverIp.c_str(),  
  104.             conNum.c_str(), websocketPort.c_str(), mqttPort.c_str(), ts.c_str());  
  105.     }  
  106.     return 0;  
  107. }  
  108.   
  109. /************************************  
  110. @ Brief:        create json data  
  111. @ Author:       woniu201   
  112. @ Created:      2017/09/06  
  113. @ Return:             
  114. ************************************/  
  115. int createJSON()  
  116. {  
  117.     Json::Value req;  
  118.     req["Result"] = 1;  
  119.     req["ResultMessage"] = "200";  
  120.   
  121.     Json::Value object1;  
  122.     object1["cpuRatio"] = "4.04";  
  123.     object1["serverIp"] = "42.159.116.104";  
  124.     object1["conNum"] = "1";  
  125.     object1["websocketPort"] = "0";  
  126.     object1["mqttPort"] = "8883";  
  127.     object1["TS"] = "1504665880572";  
  128.     Json::Value object2;  
  129.     object2["cpuRatio"] = "2.04";  
  130.     object2["serverIp"] = "42.159.122.251";  
  131.     object2["conNum"] = "2";  
  132.     object2["websocketPort"] = "0";  
  133.     object2["mqttPort"] = "8883";  
  134.     object2["TS"] = "1504665896981";  
  135.   
  136.     Json::Value jarray;  
  137.     jarray.append(object1);  
  138.     jarray.append(object2);  
  139.   
  140.     req["ResultValue"] = jarray;  
  141.   
  142.     Json::FastWriter writer;  
  143.     string jsonstr = writer.write(req);  
  144.   
  145.     printf("%s\n", jsonstr.c_str());  
  146.   
  147.     writefileAll("createJson.json", jsonstr.c_str());  
  148.     return 0;  
  149. }  
  150.   
  151. int main()  
  152. {  
  153.     /*读取Json串,解析Json串*/  
  154.     char* json = getfileAll("parseJson.json");  
  155.     parseJSON(json);  
  156.     printf("===============================\n");  
  157.   
  158.     /*组装Json串*/  
  159.     createJSON();  
  160.   
  161.     getchar();  
  162.     return 1;  
  163. }  


参考:

 

http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html

http://blog.csdn.net/yc461515457/article/details/52749575

posted @ 2018-03-16 20:01  mxp_neu  阅读(2226)  评论(0)    收藏  举报