当前位置:网站首页>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 {}
}
边栏推荐
- VIM use command
- Paper review: U2 net, u-net composed of u-net
- 腾讯云国际云服务器网络访问丢包问题解决办法
- C program design topic 18-19 final exam exercise solutions (Part 2)
- A plug-in framework for implementing registration free and login verification with hook technology
- Single blind box removal, social blind box and friend blind box program source code
- Databinding quick start (still using findviewbyid?)
- Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
- Signal integrity (SI) power integrity (PI) learning notes (I) introduction to signal integrity analysis
- Discrete mathematics and its application detailed explanation of exercises in the final exam of spring and summer semester of 2018-2019 academic year
猜你喜欢
Usage of ViewModel and livedata in jetpack
Tiktok wallpaper applet v1.0.2 function, new arrival function
Activity startup process
Creative SVG ring clock JS effect
Source code analysis the problem that fragments cannot be displayed in the custom ViewGroup
Kubernetes 架构核心组件工作原理解析
ros(25):rqt_image_view报错Unable to load plugin for transport ‘compressed‘, error string
Related operations of ansible and Playbook
Apk decompiled method (not confused)
Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
随机推荐
I suddenly find that the request dependent package in NPM has been discarded. What should I do?
Adding, deleting, modifying and checking in low build code
Xcode preview displays a bug in the content of the list view and its solution
Registration method of native method in JNI
Go crawler framework -colly actual combat (IV) -- Zhihu answer crawl (I)
@mysql
2021-04-18
Svg line animation background JS effect
【Redis实现秒杀业务④】一人一单,不可重复购买
热力图展示相关矩阵
Only positive integers can be entered in the text box
Realization of MNIST handwritten numeral recognition
Single blind box removal, social blind box and friend blind box program source code
2021-11-05
Custom control - round dot progress bar (imitating one key acceleration in security guard)
vim使用命令
Fuxin Kunpeng joins in, and dragon lizard community welcomes a new partner in format document technical service
Interesting checkbox counters
Ott marketing is booming. How should businesses invest?
Helm chart warehouse operation