rapidjson的使用例子

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

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

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

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


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<StringBuffer> 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:"<<str << endl;
	}

	rapidjson::Value & valAge = doc1["age"];
	if (valAge.IsArray())
	{
		cout << "age:" << endl;
		for (int i = 0; i < valAge.Capacity(); ++i)
		{
			rapidjson::Value & val = valAge[i];
			cout << val.GetInt() << endl;
		}
	}

	rapidjson::Value & players = doc1["players"];
	if (players.IsArray())
	{
		cout << "players:" << endl;
		for (int i = 0; i < players.Capacity(); ++i)
		{
			rapidjson::Value & val = players[i];
			cout << "id:" << val["id"].GetInt() << endl;
			cout << "name:" << val["name"].GetString() << endl;
			cout << "version:" << val["version"].GetDouble() << endl;
			cout << "vip:" << val["vip"].GetBool() << endl;
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值