赞
踩
- Json的数据结构介绍:
- /* The cJSON structure: */
- typedef struct cJSON
- {
- /*next/prev允许您遍历数组/对象链。或者,使用GetArraySize/GetArrayItem/GetObjectItem */
- struct cJSON *next;
- struct cJSON *prev;
- /* 数组或对象项将有一个子指针指向数组/对象中的项链。 */
- struct cJSON *child;
-
- /* 项目的类型,如上所述。*/
- int type;
-
- /* 字符串, if type==cJSON_String */
- char *valuestring;
- /* 数值, if type==cJSON_Number */
- int valueint;
- /* 小数数据, if type==cJSON_Number */
- double valuedouble;
-
- /* 项的名称字符串,如果此项是的子项,或在对象的子项列表中。*/
- char *string;
- } cJSON;
- Json格式文本解析:
- #define TEST2 "{\n\"auth\": \"auc_d0dd49997dd17b12f76b74fe51d0de3fd772718b\",\n\"sessionId\": \"5129110798518519880764729435382\"\n}"
- char* buffer = TEST2;
- cJSON* json = cJSON_Parse(buffer);
- cJSON* name = cJSON_GetObjectItem(json, "name");
- cJSON* num = cJSON_GetObjectItem(json, "num");
- printf("%s,%s",name->valuestring,num->valueint);
-
-
- 假设文本为:需要解析中间的pinyin,textContent,title
- "Data":
- {
- "listItems":
- [
- {
- "htmlView":"http://hanyu.baidu.com/s?wd=一飞冲天&ptype=zici",
- "mediaId":"6f7af22ba4613b869f455d569c204c69",
- "selfData":"{\"interpretation\":\"鸟儿展翅一飞,直冲云霄。比喻平时没有特殊表现,一下做出了惊人的成绩。\",\"lemma\":\"一飞冲天\",\"pinyin\":\"[yī fēi chōng tiān]\"}\n",
- "textContent":"鸟儿展翅一飞,直冲云霄。比喻平时没有特殊表现,一下做出了惊人的成绩。",
- "title":"一飞冲天"
- }
- ]
- }
-
- cJSON* Data = cJSON_GetObjectItem(json, "Data");
- cJSON* ListItems = cJSON_GetObjectItem(Data, "listItems");
- cJSON* Json_Array = cJSON_GetArrayItem(ListItems, 0);//其中[]里面为数组需要用cJSON_GetArrayItem,0代表第一个。
- cJSON* TextContent = cJSON_GetObjectItem(Json_Array, "textContent");
- cJSON* Title = cJSON_GetObjectItem(Json_Array, "title");
- cJSON* SelfData = cJSON_GetObjectItem(Json_Array, "selfData");
- cJSON* Src = cJSON_Parse(SelfData->valuestring);//selfData数据解析出来为字符串,需要再次解析为json数据才能再次解析
- cJSON* Pinyin = cJSON_GetObjectItem(Src, "pinyin");
- Json格式文本封装:将多条字符串合成一条json格式数据
- const char* client_id = "12345678";
- const char* sessionid = "abcdefg";
- cJSON *root = cJSON_CreateObject();
- cJSON_AddStringToObject(root, "authCode", client_id);
- cJSON_AddStringToObject(root, "sessionId", sessionid);//这里的添加处理字符串以外还可以添加很多类型的数据
- char *auth_resp_info = cJSON_Print(root);
- printf("%s,%s",auth_resp_info);
创建一个C++类来封装这个JSON数据:
- #include <iostream>
- #include <string>
- #include <vector>
-
- class Address {
- public:
- std::string street;
- std::string city;
- };
-
- class Person {
- public:
- std::string name;
- int age;
- Address address;
- std::vector<std::string> hobbies;
- };
-
- int main() {
- Person person;
- person.name = "John";
- person.age = 30;
- person.address.street = "123 Main St";
- person.address.city = "New York";
- person.hobbies = {"Reading", "Hiking"};
-
- // 将Person对象转换为JSON字符串
- nlohmann::json j;
- j["person"]["name"] = person.name;
- j["person"]["age"] = person.age;
- j["person"]["address"]["street"] = person.address.street;
- j["person"]["address"]["city"] = person.address.city;
- j["person"]["hobbies"] = person.hobbies;
-
- std::string jsonStr = j.dump();
- std::cout << jsonStr << std::endl;
-
- return 0;
- }
最后的数据为:
- {
- "person": {
- "name": "John",
- "age": 30,
- "address": {
- "street": "123 Main St",
- "city": "New York"
- },
- "hobbies": ["Reading", "Hiking"]
- }
- }
还有些栗子:
- json json_data;
- json_data["Header"] = {{"DSN","5ca439320d7b4adfb965a4442c791c33"}};
- json_data["Payload"] = {{"blobData",{{"longitude",""},{"latitude",""}}},{"domain","weather"},{"intent","GetGeneralMsgRequest"}};
-
- 最后形成:
- JSON string: {
- "Header": {
- "DSN": "5ca439320d7b4adfb965a4442c791c33"
- },
- "Payload": {
- "blobData": {
- "latitude": "",
- "longitude": ""
- },
- "domain": "weather",
- "intent": "GetGeneralMsgRequest"
- }
- }
-
- 或者可以这样:也可以形成上面的数据
- json j2 = R"(
- "Header": {
- "DSN": "5ca439320d7b4adfb965a4442c791c33"
- },
- "Payload": {
- "blobData": {
- "latitude": "",
- "longitude": ""
- },
- "domain": "weather",
- "intent": "GetGeneralMsgRequest"
- }
- )"_json;
- 要想打印上面封装的json的数据可以用以字符串的形式:
- json_data.dump(4)
1、RapidJSON:RapidJSON是一个非常快速的JSON解析库,它提供了简单的API来解析和生成JSON数据。
示例代码:
- #include "rapidjson/document.h"
- #include "rapidjson/writer.h"
- #include "rapidjson/stringbuffer.h"
- #include <iostream>
- #include <string>
-
- int main() {
- const char* json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
- rapidjson::Document doc;
- doc.Parse(json);
-
- if (!doc.HasParseError()) {
- std::string name = doc["name"].GetString();
- int age = doc["age"].GetInt();
- std::string city = doc["city"].GetString();
-
- std::cout << "Name: " << name << ", Age: " << age << ", City: " << city << std::endl;
- } else {
- std::cout << "JSON parse error" << std::endl;
- }
-
- return 0;
- }
2、JSON for Modern C++ (nlohmann/json):这是一个现代C++中使用的非常流行的JSON解析库。它提供了简单的API和STL兼容性,容易学习和使用。
示例代码:
- #include <nlohmann/json.hpp>
- #include <iostream>
- #include <string>
-
- int main() {
- std::string json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
- nlohmann::json j = nlohmann::json::parse(json);
-
- std::string name = j["name"];
- int age = j["age"];
- std::string city = j["city"];
-
- std::cout << "Name: " << name << ", Age: " << age << ", City: " << city << std::endl;
-
- return 0;
- }
在C++中获取多重JSON格式的数据,你需要逐级解析JSON结构,以访问嵌套在JSON对象或数组中的数据。以下是一个示例,演示如何处理多重嵌套的JSON数据。
假设你有以下JSON数据:
- {
- "person": {
- "name": "John",
- "age": 30,
- "address": {
- "street": "123 Main St",
- "city": "New York"
- },
- "hobbies": ["Reading", "Hiking"]
- }
- }
你可以使用RapidJSON或nlohmann/json等JSON解析库来处理这个JSON数据。
使用RapidJSON的示例代码:
- #include "rapidjson/document.h"
- #include "rapidjson/writer.h"
- #include "rapidjson/stringbuffer.h"
- #include <iostream>
- #include <string>
-
- int main() {
- const char* json = "{\"person\":{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\"},\"hobbies\":[\"Reading\",\"Hiking\"]}}";
- rapidjson::Document doc;
- doc.Parse(json);
-
- if (!doc.HasParseError()) {
- const rapidjson::Value& person = doc["person"];
- std::string name = person["name"].GetString();
- int age = person["age"].GetInt();
-
- const rapidjson::Value& address = person["address"];
- std::string street = address["street"].GetString();
- std::string city = address["city"].GetString();
-
- const rapidjson::Value& hobbies = person["hobbies"];
- if (hobbies.IsArray()) {
- for (rapidjson::SizeType i = 0; i < hobbies.Size(); i++) {
- std::string hobby = hobbies[i].GetString();
- std::cout << "Hobby " << i + 1 << ": " << hobby << std::endl;
- }
- }
-
- std::cout << "Name: " << name << ", Age: " << age << std::endl;
- std::cout << "Address: " << street << ", " << city << std::endl;
- } else {
- std::cout << "JSON parse error" << std::endl;
- }
-
- return 0;
- }
使用nlohmann/json的示例代码:
- #include <nlohmann/json.hpp>
- #include <iostream>
- #include <string>
-
- int main() {
- std::string json = "{\"person\":{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\"},\"hobbies\":[\"Reading\",\"Hiking\"]}}";
- nlohmann::json j = nlohmann::json::parse(json);
-
- std::string name = j["person"]["name"];
- int age = j["person"]["age"];
-
- std::string street = j["person"]["address"]["street"];
- std::string city = j["person"]["address"]["city"];
-
- for (const auto& hobby : j["person"]["hobbies"]) {
- std::string hobbyStr = hobby;
- std::cout << "Hobby: " << hobbyStr << std::endl;
- }
-
- std::cout << "Name: " << name << ", Age: " << age << std::endl;
- std::cout << "Address: " << street << ", " << city << std::endl;
-
- return 0;
- }
- #include <nlohmann/json.hpp>
- #include <iostream>
- #include <string>
-
- int main() {
- std::string json = R"(
- {
- "Header": {
- "sessionId": "1648612124933560_v20ZmHxNa4yx3",
- "code": 200,
- "message": "业务服务返回消息:StatusOK"
- },
- "Payload": {
- "groupList": [
- {
- "groupName": "巅峰榜",
- "groupTopList": [
- {
- "listenNum": 18835312,
- "showTime": "2022-03-30",
- "songInfos": [
- {
- "singerId": 4658,
- "singerMId": "000ZVS6E1f6f0d",
- "singerName": "杨丞琳",
- "songId": 648765,
- "songMId": "004XNJ8Y2iD3VL",
- "songName": "匿名的好友"
- },
- {
- "singerId": 143,
- "singerMId": "003Nz2So3XXYek",
- "singerName": "陈奕迅",
- "songId": 331839675,
- "songMId": "003UkWuI0E8U0l",
- "songName": "孤勇者"
- }
- ],
- "topBannerPic": "http://y.gtimg.cn/music/photo_new/T003R500x500M000001namcx2Rs3fW.jpg",
- "topHeaderPic": "http://y.gtimg.cn/music/photo_new/T002R300x300M000000jcKFG0sQrD0.jpg",
- "topId": 62,
- "topName": "飙升榜",
- "totalNum": 100
- }
- ]
- }
- ],
- "msg": "OK",
- "ret": 0,
- "sessionId": "1648612124933560_v20ZmHxNa4yx3"
- }
- }
- )";
-
- nlohmann::json j = nlohmann::json::parse(json);
-
- if (j.contains("Header") && j.contains("Payload")) {
- const auto& header = j["Header"];
- const auto& payload = j["Payload"];
-
- std::string sessionId = header["sessionId"];
- int code = header["code"];
- std::string message = header["message"];
-
- std::string msg = payload["msg"];
- int ret = payload["ret"];
- std::string payloadSessionId = payload["sessionId"];
-
- const auto& groupList = payload["groupList"];
- if (groupList.is_array()) {
- for (const auto& group : groupList) {
- std::string groupName = group["groupName"];
- const auto& groupTopList = group["groupTopList"];
- if (groupTopList.is_array()) {
- for (const auto& top : groupTopList) {
- int listenNum = top["listenNum"];
- std::string showTime = top["showTime"];
- int topId = top["topId"];
- std::string topName = top["topName"];
- int totalNum = top["totalNum"];
-
- const auto& songInfos = top["songInfos"];
- if (songInfos.is_array()) {
- for (const auto& songInfo : songInfos) {
- int singerId = songInfo["singerId"];
- std::string singerMId = songInfo["singerMId"];
- std::string singerName = songInfo["singerName"];
- int songId = songInfo["songId"];
- std::string songMId = songInfo["songMId"];
- std::string songName = songInfo["songName"];
-
- // 打印解析结果
- std::cout << "Song Info:" << std::endl;
- std::cout << "Singer ID: " << singerId << std::endl;
- std::cout << "Singer MId: " << singerMId << std::endl;
- std::cout << "Singer Name: " << singerName << std::endl;
- std::cout << "Song ID: " << songId << std::endl;
- std::cout << "Song MId: " << songMId << std::endl;
- std::cout << "Song Name: " << songName << std::endl;
- }
- } else {
- std::cout << "songInfos is not an array" << std::endl;
- }
-
- // 打印解析结果
- std::cout << "Listen Num: " << listenNum << std::endl;
- std::cout << "Show Time: " << showTime << std::endl;
- std::cout << "Top ID: " << topId << std::endl;
- std::cout << "Top Name: " << topName << std::endl;
- std::cout << "Total Num: " << totalNum << std::endl;
- }
- } else {
- std::cout << "groupTopList is not an array" << std::endl;
- }
-
- // 打印解析结果
- std::cout << "Group Name: " << groupName << std::endl;
- }
- } else {
- std::cout << "groupList is not an array" << std::endl;
- }
- } else {
- std::cout << "Header or Payload is not present in the JSON" << std::endl;
- }
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。