当前位置:网站首页>QT(36)-rapidjson解析嵌套的json
QT(36)-rapidjson解析嵌套的json
2022-06-24 20:06:00 【多云的夏天】
前面一篇写了最简单的调用。本篇描述的是嵌套解析。
value值:字符串,数字,数组,object,嵌套数组,Bool
生成json文件:
//生成一串如下的json格式字符串,并解析
//value值:字符串,数字,数组,object,嵌套数组,Bool
// {
// "name":"test",
// "age":20,
// "letter":["a","b","c"],
// "location": {"province":"fujian","city":"xiamen","number":16}
// "book":[{"name":"book1", "isbn":"123"},{"name":"book2","isbn":"456"}],
// "healthy":true,
// }
rapidjson::Document jsonDoc; //1.生成一个dom元素Document
rapidjson::Document::AllocatorType &allocator = jsonDoc.GetAllocator();
jsonDoc.SetObject(); // 设置root dom为object型
jsonDoc.AddMember("name", "test", allocator); //2.添加子节点 字符串型
jsonDoc.AddMember("age", 20, allocator);
rapidjson::Value letterArray(rapidjson::kArrayType);
letterArray.PushBack("a", allocator);
letterArray.PushBack("b", allocator);
letterArray.PushBack("c", allocator);
jsonDoc.AddMember("letter", letterArray, allocator); //3.添加子节点 数组型
rapidjson::Value locationObj(rapidjson::kObjectType);
locationObj.AddMember("province", "fujian", allocator);
locationObj.AddMember("city", "xiamen", allocator);
locationObj.AddMember("number", 16, allocator);
jsonDoc.AddMember("location", locationObj, allocator); //4.添加子节点 object 嵌套object
rapidjson::Value bookArray(rapidjson::kArrayType);
rapidjson::Value book1(rapidjson::kObjectType);
book1.AddMember("name", "book1", allocator);
book1.AddMember("isbn", "123", allocator);
bookArray.PushBack(book1, allocator);
rapidjson::Value book2(rapidjson::kObjectType);
book2.AddMember("name", "book2", allocator);
book2.AddMember("isbn", "456", allocator);
bookArray.PushBack(book2, allocator);
jsonDoc.AddMember("book", bookArray, allocator); //5.添加子节点 数组嵌套object
jsonDoc.AddMember("healthy", true, allocator); //5.添加子节点 添加bool类型值
// jsonDoc.AddMember("sports", NULL, allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
jsonDoc.Accept(writer);
std::string strJson = std::string( buffer.GetString() );
printf("-----生成的Json:\n%s", strJson.c_str());
std::string strPath ="C:\\JsonFile.txt";
FILE* myFile = fopen(strPath.c_str(), "w"); 写到文件windows平台要使用wb
if (myFile)
{
fputs(buffer.GetString(), myFile);
fclose(myFile);
}解析json格式:
rapidjson::Document newDoc;
std::string strPath ="C:\\JsonFile.txt";
FILE* myFile = fopen(strPath.c_str(), "r"); //windows平台使用rb
if (myFile)
{
char buffer[256];
FileReadStream inputStream(myFile,buffer,sizeof(buffer)); //1.创建一个输入流
newDoc.ParseStream<0>(inputStream); //2.将读取的内容转换为dom元素
fclose(myFile); //3.关闭文件,很重要
}
if (newDoc.HasParseError())
{
printf("Json Parse error:%d\n", newDoc.GetParseError());
}
else
{
//1.解析 "name":"test"
if (newDoc.HasMember("name"))
{
printf("name:%s\n", newDoc["name"].GetString());
}
else
{}
//2.解析 "age":20
if (newDoc.HasMember("age"))
{
printf("age:%d\n", newDoc["age"].GetInt());
}
else
{}
//3.解析 array 数组 "letter":["a","b","c"],
if (newDoc.HasMember("letter"))
{
rapidjson::Value letter;
letter = newDoc["letter"];
if (letter.IsArray() && !letter.Empty())
{
for (rapidjson::SizeType i = 0; i < letter.Size(); i++)
{
printf("letter:%s\n", letter[i].GetString());
}
}
else
{}
}
else {}
//3.解析 object {"province":"fujian","city":"xiamen","number":16}
if (newDoc.HasMember("location"))
{
rapidjson::Value location;
location = newDoc["location"];
if (location.IsObject())
{
if (location.HasMember("province"))
{
printf("location:province:%s\n", location["province"].GetString());
}
else {}
if (location.HasMember("city"))
{
printf("location:city:%s\n", location["city"].GetString());
}
else {}
if (location.HasMember("number"))
{
printf("location:number:%d\n", location["number"].GetInt());
}
else {}
}
else {}
}
else {}
//4.解析 数组嵌套object [{"name":"book1", "isbn":"123"},{"name":"book2","isbn":"456"}]
if (newDoc.HasMember("book"))
{
rapidjson::Value book;
book = newDoc["book"];
//先取Array
if (book.IsArray() && !book.Empty())
{
rapidjson::Value tempBook;
for (rapidjson::SizeType i = 0; i < book.Size(); i++)
{
tempBook = book[i];
if (tempBook.IsObject())
{
if (tempBook.HasMember("name") && tempBook.HasMember("isbn"))
{
printf("book:%d:name:%s, isbn:%s\n", i, tempBook["name"].GetString(), tempBook["isbn"].GetString());
}
else {}
}
else {}
}
}
else {}
}
else {}
if (newDoc.HasMember("healthy"))
{
if (newDoc["healthy"].GetBool())
{
printf("healthy:true\n");
}
else
{
printf("healthy:false\n");
}
}
else {}
}
边栏推荐
- 5-minute NLP: summary of 3 pre training libraries for rapid realization of NER
- 腾讯云国际云服务器网络访问丢包问题解决办法
- Uniapp encapsulated incentive advertisement, screen insert advertisement and banner advertisement
- Collective example
- Kubernetes 架构核心组件工作原理解析
- The picture of wechat official account can not be displayed normally
- A website for programmers with a monthly salary of 30K
- Use of JMeter easynmon
- ServerSocket and socket connection
- redis + lua实现分布式接口限流实现方案
猜你喜欢

Tiktok wallpaper applet v1.0.2 function, new arrival function
Design and practice of vivo server monitoring architecture

【Redis实现秒杀业务④】一人一单,不可重复购买

C WinForm maximizes occlusion of the taskbar and full screen display

UE4 WebBrowser chart cannot display problems

在企业级开发过程中我发现有位同事用select * from where 条件 for update
![[leaderboard] Carla leaderboard leaderboard leaderboard operation and participation in hands-on teaching](/img/bd/b176e93ee6fa2125f021bcad3025c2.png)
[leaderboard] Carla leaderboard leaderboard leaderboard operation and participation in hands-on teaching

Xcode preview displays a bug in the content of the list view and its solution

How to quickly open traffic master for wechat applet

无人驾驶: 对多传感器融合的一些思考
随机推荐
Android SQLite database
Binder mechanism and Aidl communication example
What is test development? Can you find a job at this stage?
移动安全工具-apktool
Helm chart warehouse operation
Usage of assert
Fuxin Kunpeng joins in, and dragon lizard community welcomes a new partner in format document technical service
Realization of MNIST handwritten numeral recognition
Infotnews | is the development of domestic NFT limited to digital collections?
More pictures | explain the Nacos parameters in detail!
adb shell getevent
Custom animation (simulated win10 loading animation)
[figure database performance and scenario test sharp tool ldbc SNB] series I: introduction to data generator & Application to ges service
无人驾驶: 对多传感器融合的一些思考
JDBC - database connection
5-minute NLP: summary of 3 pre training libraries for rapid realization of NER
大厂高频软件测试面试题和答案都帮你准备好啦,备战金九银十
Decoupling pages and components using lifecycle
Is it so difficult to calculate the REM size of the web page according to the design draft?
Xcode预览(Preview)显示List视图内容的一个Bug及解决