C++操作json

具体操作代码如下:

#include<iostream>
#include<string>
#include "../include/rapidjson/document.h"
#include "../include/rapidjson/writer.h"
#include "../include/rapidjson/stringbuffer.h"

using namespace rapidjson;


std::string ToJson()
{
	Document doc;
	doc.SetObject();
	Document::AllocatorType &typeAllocate = doc.GetAllocator();

	//单个key
	doc.AddMember("id", 10, typeAllocate);
	doc.AddMember("name", "test", typeAllocate);
	//数组
	Value valueArr(rapidjson::kArrayType);
	for (int nIndex = 0; nIndex < 2; ++nIndex)
	{
		Value valueData(rapidjson::kObjectType);
		valueData.AddMember("C++", "666", typeAllocate);
		valueData.AddMember("Java", "1212", typeAllocate);

		valueArr.PushBack(valueData, typeAllocate);
	}
	//添加变量字符串
	std::string strTag("hero");
	doc.AddMember("tag", rapidjson::Value(strTag.c_str(), typeAllocate), typeAllocate);
	
	doc.AddMember("skill", valueArr, typeAllocate);

	StringBuffer buffer;
	Writer<StringBuffer>  writer(buffer);
	doc.Accept(writer);
	std::string strMsg = buffer.GetString();
	std::cout << strMsg.c_str() << std::endl;
	return strMsg;
}

void ParseJson(const std::string& strData)
{
	std::cout << "********开始解析json数据***********\n";
	Document doc;
	doc.Parse(strData.c_str());
	if (doc.HasParseError())
	{
		std::cout << "解析json失败,Src:" << strData.c_str() << std::endl;
		return;
	}
	Value &vData = doc["id"];
	std::cout << "ID:" << vData.GetInt() << "\n";

	vData = doc["name"];
	std::cout << "Name:" << vData.GetString() << "\n";

	vData = doc["skill"];
	for (int nIndex = 0; nIndex < vData.Size(); ++nIndex)
	{
		Value& valueSkill = vData[nIndex];
		std::cout << "Name:" << valueSkill["C++"].GetString() << ",";
		std::cout << "Name:" << valueSkill["Java"].GetString() << "\n";
	}

}

int main()
{
	std::string strRst(ToJson());
	ParseJson(strRst);

	system("pause");
	return 0;
}
发布了35 篇原创文章 · 获赞 2 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Wite_Chen/article/details/83689389