QT(36)-rapidjson解析嵌套的json

本文详细介绍了如何利用RapidJSON库生成包含字符串、数字、数组、嵌套对象及布尔值的JSON格式字符串,并将其写入文件。同时,展示了从文件读取并解析JSON内容的方法,包括遍历并打印各种类型的JSON节点。
摘要由CSDN通过智能技术生成

前面一篇写了最简单的调用。本篇描述的是嵌套解析。
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 {}
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值