JsonCpp使用方法详解

时间:2023-03-09 16:46:22
JsonCpp使用方法详解

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:

  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文件进行解析:

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

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

  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就是带有格式的写入,看起来会比较友好。

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

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

  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
}

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

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

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

参考:

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

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