JsonCpp经典入门

前端之家收集整理的这篇文章主要介绍了JsonCpp经典入门前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.JsonCpp

1.1.JsonCpp简介

JSON is a lightweight data-interchange format. It can represent numbers,strings,ordered sequences of values,and collections of name/value pairs.

JsonCpp is a C++ library that allows manipulating JSON values,including serialization and deserialization to and from strings. It can also preserve existing comment in unserialization/serialization steps,making it a convenient format to store user input files.

1.2.JsonCpp环境搭建

1.2.1.下载地址

https://github.com/open-source-parsers/jsoncpp#generating-amalgamated-source-and-header

1.2.2.Qt中JsonCpp安装

① 解压jsoncpp-master.zip包
② 在根目录下,运行python amalgamate.py
③ 在根目录中生成dist文件夹包含三个文件dist/json/json-forwards.h dist/json/json.h dist/json.cpp
④ 在Qt工程目录下,生成json文件夹,并拷贝json目录下。
⑤ 在Qt工程中添加现有文件即可。

1.3.读写JsonCpp

1.3.1.写

  1. #include <iostream>
  2. #include <fstream>
  3. #include "json/json.h"
  4. using namespace Json;
  5. using namespace std;
  6.  
  7.  
  8. #if 0
  9. {
  10. "animals":{
  11. "dog":[
  12. {
  13. "name":"Rufus","age":15
  14. },{
  15. "name":"Marty","age":null
  16. }
  17. ]
  18. }
  19. }
  20. #endif
  21.  
  22. void writeJson()
  23. {
  24. Value rootAnimalsObj;
  25. Value dog;
  26. Value dogArray;
  27.  
  28. Value dogValueItem1;
  29. dogValueItem1["name"] = "Rufus";
  30. dogValueItem1["age"] = 15;
  31.  
  32. Value dogValueItem2;
  33. dogValueItem2["name"] = "Marty";
  34. dogValueItem2["age"] = "";
  35.  
  36. dogArray.append(dogValueItem1);
  37. dogArray.append(dogValueItem2);
  38. dog["dog"] = dogArray;
  39. rootAnimalsObj["animals"] = dog;
  40.  
  41. string str = rootAnimalsObj.toStyledString();
  42. cout<<str;
  43.  
  44. ofstream ofs;
  45. ofs.open("test_write.json");
  46. ofs << str;
  47. ofs.close();
  48.  
  49. return;
  50. }
  51.  
  52. int main()
  53. {
  54. writeJson();
  55. return 0;
  56. }

1.3.2.读

  1. #include <iostream>
  2. #include <fstream>
  3. #include "json/json.h"
  4. using namespace Json;
  5. using namespace std;
  6.  
  7.  
  8. #if 0
  9. {
  10. "animals":{
  11. "dog":[
  12. {
  13. "name":"Rufus","age":null
  14. }
  15. ]
  16. }
  17. }
  18. #endif
  19.  
  20.  
  21.  
  22. void readJson()
  23. {
  24. ifstream is("aa.json");
  25. if(!is)
  26. {
  27. cout<<"open error"<<endl;
  28. return;
  29. }
  30. Reader reader;
  31. Value root;
  32.  
  33. if(reader.parse(is,root))
  34. {
  35. cout<<root<<endl;
  36. Value & dogArr = root["animals"]["dog"];
  37. for(int i=0; i<dogArr.size(); i++)
  38. {
  39. cout<<dogArr[i]["name"].asString()<<endl;
  40. cout<<dogArr[i]["age"].asInt()<<endl;
  41. }
  42.  
  43. }
  44.  
  45. is.close();
  46. }
  47.  
  48. int main()
  49. {
  50. readJson();
  51. return 0;
  52. }

猜你在找的Json相关文章