rapidjson的使用例子

最近在使用json, 由以前的jsoncpp转为rapidjson, 听说这个效率高一点;

不过我觉得比较好的就是rapidjson不需要库,只要头文件就可以了

记录下来方便自己以后使用

#if 1
#include 
#include 
#include 
#include 
#include 


using namespace rapidjson;
using namespace std;

int main(int argc, char *argv[])
{
	Document document;
	document.SetObject();
	Document::AllocatorType& allocator = document.GetAllocator();

	Value array(kArrayType);

	for (int i = 0; i < 2; i++)
	{
		Value object(kObjectType);
		object.AddMember("id", 1, allocator);
		object.AddMember("name", "test", allocator);
		object.AddMember("version", 1.01, allocator);
		object.AddMember("vip", true, allocator);
		array.PushBack(object, allocator);
	}

	document.AddMember("title", "PLAYER INFO", allocator);
	document.AddMember("players", array, allocator);
	Value age(kArrayType);
	for (int j = 0; j < 5;j++)
	{
		Value object(kNumberType);
		object.SetInt(j);
		age.PushBack(object, allocator);
	}

	document.AddMember("age",age,allocator);

	StringBuffer buffer;
	Writer writer(buffer);
	document.Accept(writer);
	const char * out = buffer.GetString();
	cout << out << endl;

	cout << "-------------analyze--------------" << endl;
	/*
	{
		"title":"PLAYER INFO",
		"players":[
			{
				"id":1,
				"name":"test",
				"version":1.01,
				"vip":true
			},
			{
				"id":1,
				"name":"test",
				"version":1.01,
				"vip":true
			}
		],
		"age":[0,1,2,3,4]
	}
	*/
	Document doc1;
	doc1.Parse<0>(out);               ///< 通过Parse方法将Json数据解析出来
	if (doc1.HasParseError())
	{
		cout << "GetParseError%s\n" << doc1.GetParseError() << endl;
		return 1;
	}
	rapidjson::Value & valString = doc1["title"];
	if (valString.IsString())
	{
		const char * str = valString.GetString();
		cout << "title:"<


你可能感兴趣的:(C++)