当前位置:   article > 正文

C、C++中对json格式数据的解析和封装_c++ json

c++ json

C:首先需要调库:#include <cJSON.h>

  1. Json的数据结构介绍:
  2. /* The cJSON structure: */
  3. typedef struct cJSON
  4. {
  5. /*next/prev允许您遍历数组/对象链。或者,使用GetArraySize/GetArrayItem/GetObjectItem */
  6. struct cJSON *next;
  7. struct cJSON *prev;
  8. /* 数组或对象项将有一个子指针指向数组/对象中的项链。 */
  9. struct cJSON *child;
  10. /* 项目的类型,如上所述。*/
  11. int type;
  12. /* 字符串, if type==cJSON_String */
  13. char *valuestring;
  14. /* 数值, if type==cJSON_Number */
  15. int valueint;
  16. /* 小数数据, if type==cJSON_Number */
  17. double valuedouble;
  18. /* 项的名称字符串,如果此项是的子项,或在对象的子项列表中。*/
  19. char *string;
  20. } cJSON;
  1. Json格式文本解析:
  2. #define TEST2 "{\n\"auth\": \"auc_d0dd49997dd17b12f76b74fe51d0de3fd772718b\",\n\"sessionId\": \"5129110798518519880764729435382\"\n}"
  3. char* buffer = TEST2;
  4. cJSON* json = cJSON_Parse(buffer);
  5. cJSON* name = cJSON_GetObjectItem(json, "name");
  6. cJSON* num = cJSON_GetObjectItem(json, "num");
  7. printf("%s,%s",name->valuestring,num->valueint);
  8. 假设文本为:需要解析中间的pinyin,textContent,title
  9. "Data":
  10. {
  11. "listItems":
  12. [
  13. {
  14. "htmlView":"http://hanyu.baidu.com/s?wd=一飞冲天&ptype=zici",
  15. "mediaId":"6f7af22ba4613b869f455d569c204c69",
  16. "selfData":"{\"interpretation\":\"鸟儿展翅一飞,直冲云霄。比喻平时没有特殊表现,一下做出了惊人的成绩。\",\"lemma\":\"一飞冲天\",\"pinyin\":\"[yī fēi chōng tiān]\"}\n",
  17. "textContent":"鸟儿展翅一飞,直冲云霄。比喻平时没有特殊表现,一下做出了惊人的成绩。",
  18. "title":"一飞冲天"
  19. }
  20. ]
  21. }
  22. cJSON* Data = cJSON_GetObjectItem(json, "Data");
  23. cJSON* ListItems = cJSON_GetObjectItem(Data, "listItems");
  24. cJSON* Json_Array = cJSON_GetArrayItem(ListItems, 0);//其中[]里面为数组需要用cJSON_GetArrayItem,0代表第一个。
  25. cJSON* TextContent = cJSON_GetObjectItem(Json_Array, "textContent");
  26. cJSON* Title = cJSON_GetObjectItem(Json_Array, "title");
  27. cJSON* SelfData = cJSON_GetObjectItem(Json_Array, "selfData");
  28. cJSON* Src = cJSON_Parse(SelfData->valuestring);//selfData数据解析出来为字符串,需要再次解析为json数据才能再次解析
  29. cJSON* Pinyin = cJSON_GetObjectItem(Src, "pinyin");
  1. Json格式文本封装:将多条字符串合成一条json格式数据
  2. const char* client_id = "12345678";
  3. const char* sessionid = "abcdefg";
  4. cJSON *root = cJSON_CreateObject();
  5. cJSON_AddStringToObject(root, "authCode", client_id);
  6. cJSON_AddStringToObject(root, "sessionId", sessionid);//这里的添加处理字符串以外还可以添加很多类型的数据
  7. char *auth_resp_info = cJSON_Print(root);
  8. printf("%s,%s",auth_resp_info);

C++封装json格式数据:

创建一个C++类来封装这个JSON数据

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. class Address {
  5. public:
  6. std::string street;
  7. std::string city;
  8. };
  9. class Person {
  10. public:
  11. std::string name;
  12. int age;
  13. Address address;
  14. std::vector<std::string> hobbies;
  15. };
  16. int main() {
  17. Person person;
  18. person.name = "John";
  19. person.age = 30;
  20. person.address.street = "123 Main St";
  21. person.address.city = "New York";
  22. person.hobbies = {"Reading", "Hiking"};
  23. // 将Person对象转换为JSON字符串
  24. nlohmann::json j;
  25. j["person"]["name"] = person.name;
  26. j["person"]["age"] = person.age;
  27. j["person"]["address"]["street"] = person.address.street;
  28. j["person"]["address"]["city"] = person.address.city;
  29. j["person"]["hobbies"] = person.hobbies;
  30. std::string jsonStr = j.dump();
  31. std::cout << jsonStr << std::endl;
  32. return 0;
  33. }

 最后的数据为:

  1. {
  2. "person": {
  3. "name": "John",
  4. "age": 30,
  5. "address": {
  6. "street": "123 Main St",
  7. "city": "New York"
  8. },
  9. "hobbies": ["Reading", "Hiking"]
  10. }
  11. }

还有些栗子: 

  1. json json_data;
  2. json_data["Header"] = {{"DSN","5ca439320d7b4adfb965a4442c791c33"}};
  3. json_data["Payload"] = {{"blobData",{{"longitude",""},{"latitude",""}}},{"domain","weather"},{"intent","GetGeneralMsgRequest"}};
  4. 最后形成:
  5. JSON string: {
  6. "Header": {
  7. "DSN": "5ca439320d7b4adfb965a4442c791c33"
  8. },
  9. "Payload": {
  10. "blobData": {
  11. "latitude": "",
  12. "longitude": ""
  13. },
  14. "domain": "weather",
  15. "intent": "GetGeneralMsgRequest"
  16. }
  17. }
  18. 或者可以这样:也可以形成上面的数据
  19. json j2 = R"(
  20. "Header": {
  21. "DSN": "5ca439320d7b4adfb965a4442c791c33"
  22. },
  23. "Payload": {
  24. "blobData": {
  25. "latitude": "",
  26. "longitude": ""
  27. },
  28. "domain": "weather",
  29. "intent": "GetGeneralMsgRequest"
  30. }
  31. )"_json;
  1. 要想打印上面封装的json的数据可以用以字符串的形式:
  2. json_data.dump(4)

C++解析json格式数据: 

1、RapidJSON:RapidJSON是一个非常快速的JSON解析库,它提供了简单的API来解析和生成JSON数据。

示例代码:

  1. #include "rapidjson/document.h"
  2. #include "rapidjson/writer.h"
  3. #include "rapidjson/stringbuffer.h"
  4. #include <iostream>
  5. #include <string>
  6. int main() {
  7. const char* json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
  8. rapidjson::Document doc;
  9. doc.Parse(json);
  10. if (!doc.HasParseError()) {
  11. std::string name = doc["name"].GetString();
  12. int age = doc["age"].GetInt();
  13. std::string city = doc["city"].GetString();
  14. std::cout << "Name: " << name << ", Age: " << age << ", City: " << city << std::endl;
  15. } else {
  16. std::cout << "JSON parse error" << std::endl;
  17. }
  18. return 0;
  19. }

 2、JSON for Modern C++ (nlohmann/json):这是一个现代C++中使用的非常流行的JSON解析库。它提供了简单的API和STL兼容性,容易学习和使用。

示例代码:

  1. #include <nlohmann/json.hpp>
  2. #include <iostream>
  3. #include <string>
  4. int main() {
  5. std::string json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
  6. nlohmann::json j = nlohmann::json::parse(json);
  7. std::string name = j["name"];
  8. int age = j["age"];
  9. std::string city = j["city"];
  10. std::cout << "Name: " << name << ", Age: " << age << ", City: " << city << std::endl;
  11. return 0;
  12. }

C++中解析多重json格式的数据:

在C++中获取多重JSON格式的数据,你需要逐级解析JSON结构,以访问嵌套在JSON对象或数组中的数据。以下是一个示例,演示如何处理多重嵌套的JSON数据。

假设你有以下JSON数据:

  1. {
  2. "person": {
  3. "name": "John",
  4. "age": 30,
  5. "address": {
  6. "street": "123 Main St",
  7. "city": "New York"
  8. },
  9. "hobbies": ["Reading", "Hiking"]
  10. }
  11. }

你可以使用RapidJSON或nlohmann/json等JSON解析库来处理这个JSON数据。

使用RapidJSON的示例代码:

  1. #include "rapidjson/document.h"
  2. #include "rapidjson/writer.h"
  3. #include "rapidjson/stringbuffer.h"
  4. #include <iostream>
  5. #include <string>
  6. int main() {
  7. const char* json = "{\"person\":{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\"},\"hobbies\":[\"Reading\",\"Hiking\"]}}";
  8. rapidjson::Document doc;
  9. doc.Parse(json);
  10. if (!doc.HasParseError()) {
  11. const rapidjson::Value& person = doc["person"];
  12. std::string name = person["name"].GetString();
  13. int age = person["age"].GetInt();
  14. const rapidjson::Value& address = person["address"];
  15. std::string street = address["street"].GetString();
  16. std::string city = address["city"].GetString();
  17. const rapidjson::Value& hobbies = person["hobbies"];
  18. if (hobbies.IsArray()) {
  19. for (rapidjson::SizeType i = 0; i < hobbies.Size(); i++) {
  20. std::string hobby = hobbies[i].GetString();
  21. std::cout << "Hobby " << i + 1 << ": " << hobby << std::endl;
  22. }
  23. }
  24. std::cout << "Name: " << name << ", Age: " << age << std::endl;
  25. std::cout << "Address: " << street << ", " << city << std::endl;
  26. } else {
  27. std::cout << "JSON parse error" << std::endl;
  28. }
  29. return 0;
  30. }

使用nlohmann/json的示例代码:

  1. #include <nlohmann/json.hpp>
  2. #include <iostream>
  3. #include <string>
  4. int main() {
  5. std::string json = "{\"person\":{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\"},\"hobbies\":[\"Reading\",\"Hiking\"]}}";
  6. nlohmann::json j = nlohmann::json::parse(json);
  7. std::string name = j["person"]["name"];
  8. int age = j["person"]["age"];
  9. std::string street = j["person"]["address"]["street"];
  10. std::string city = j["person"]["address"]["city"];
  11. for (const auto& hobby : j["person"]["hobbies"]) {
  12. std::string hobbyStr = hobby;
  13. std::cout << "Hobby: " << hobbyStr << std::endl;
  14. }
  15. std::cout << "Name: " << name << ", Age: " << age << std::endl;
  16. std::cout << "Address: " << street << ", " << city << std::endl;
  17. return 0;
  18. }
  1. #include <nlohmann/json.hpp>
  2. #include <iostream>
  3. #include <string>
  4. int main() {
  5. std::string json = R"(
  6. {
  7. "Header": {
  8. "sessionId": "1648612124933560_v20ZmHxNa4yx3",
  9. "code": 200,
  10. "message": "业务服务返回消息:StatusOK"
  11. },
  12. "Payload": {
  13. "groupList": [
  14. {
  15. "groupName": "巅峰榜",
  16. "groupTopList": [
  17. {
  18. "listenNum": 18835312,
  19. "showTime": "2022-03-30",
  20. "songInfos": [
  21. {
  22. "singerId": 4658,
  23. "singerMId": "000ZVS6E1f6f0d",
  24. "singerName": "杨丞琳",
  25. "songId": 648765,
  26. "songMId": "004XNJ8Y2iD3VL",
  27. "songName": "匿名的好友"
  28. },
  29. {
  30. "singerId": 143,
  31. "singerMId": "003Nz2So3XXYek",
  32. "singerName": "陈奕迅",
  33. "songId": 331839675,
  34. "songMId": "003UkWuI0E8U0l",
  35. "songName": "孤勇者"
  36. }
  37. ],
  38. "topBannerPic": "http://y.gtimg.cn/music/photo_new/T003R500x500M000001namcx2Rs3fW.jpg",
  39. "topHeaderPic": "http://y.gtimg.cn/music/photo_new/T002R300x300M000000jcKFG0sQrD0.jpg",
  40. "topId": 62,
  41. "topName": "飙升榜",
  42. "totalNum": 100
  43. }
  44. ]
  45. }
  46. ],
  47. "msg": "OK",
  48. "ret": 0,
  49. "sessionId": "1648612124933560_v20ZmHxNa4yx3"
  50. }
  51. }
  52. )";
  53. nlohmann::json j = nlohmann::json::parse(json);
  54. if (j.contains("Header") && j.contains("Payload")) {
  55. const auto& header = j["Header"];
  56. const auto& payload = j["Payload"];
  57. std::string sessionId = header["sessionId"];
  58. int code = header["code"];
  59. std::string message = header["message"];
  60. std::string msg = payload["msg"];
  61. int ret = payload["ret"];
  62. std::string payloadSessionId = payload["sessionId"];
  63. const auto& groupList = payload["groupList"];
  64. if (groupList.is_array()) {
  65. for (const auto& group : groupList) {
  66. std::string groupName = group["groupName"];
  67. const auto& groupTopList = group["groupTopList"];
  68. if (groupTopList.is_array()) {
  69. for (const auto& top : groupTopList) {
  70. int listenNum = top["listenNum"];
  71. std::string showTime = top["showTime"];
  72. int topId = top["topId"];
  73. std::string topName = top["topName"];
  74. int totalNum = top["totalNum"];
  75. const auto& songInfos = top["songInfos"];
  76. if (songInfos.is_array()) {
  77. for (const auto& songInfo : songInfos) {
  78. int singerId = songInfo["singerId"];
  79. std::string singerMId = songInfo["singerMId"];
  80. std::string singerName = songInfo["singerName"];
  81. int songId = songInfo["songId"];
  82. std::string songMId = songInfo["songMId"];
  83. std::string songName = songInfo["songName"];
  84. // 打印解析结果
  85. std::cout << "Song Info:" << std::endl;
  86. std::cout << "Singer ID: " << singerId << std::endl;
  87. std::cout << "Singer MId: " << singerMId << std::endl;
  88. std::cout << "Singer Name: " << singerName << std::endl;
  89. std::cout << "Song ID: " << songId << std::endl;
  90. std::cout << "Song MId: " << songMId << std::endl;
  91. std::cout << "Song Name: " << songName << std::endl;
  92. }
  93. } else {
  94. std::cout << "songInfos is not an array" << std::endl;
  95. }
  96. // 打印解析结果
  97. std::cout << "Listen Num: " << listenNum << std::endl;
  98. std::cout << "Show Time: " << showTime << std::endl;
  99. std::cout << "Top ID: " << topId << std::endl;
  100. std::cout << "Top Name: " << topName << std::endl;
  101. std::cout << "Total Num: " << totalNum << std::endl;
  102. }
  103. } else {
  104. std::cout << "groupTopList is not an array" << std::endl;
  105. }
  106. // 打印解析结果
  107. std::cout << "Group Name: " << groupName << std::endl;
  108. }
  109. } else {
  110. std::cout << "groupList is not an array" << std::endl;
  111. }
  112. } else {
  113. std::cout << "Header or Payload is not present in the JSON" << std::endl;
  114. }
  115. return 0;
  116. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/553872
推荐阅读
相关标签
  

闽ICP备14008679号