加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

rapidjson的使用例子

发布时间:2020-12-16 18:51:10 所属栏目:百科 来源:网络整理
导读:最近在使用json,由以前的jsoncpp转为rapidjson,听说这个效率高一点; 不过我觉得比较好的就是rapidjson不需要库,只要头文件就可以了 记录下来方便自己以后使用 #if 1#include string#include iostream#include rapidjson/document.h#include rapidjson/writ

最近在使用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,"vip":true
			}
		],"age":[0,2,3,4]
	}
	*/
	Document doc1;
	doc1.Parse<0>(out);               ///< 通过Parse方法将Json数据解析出来
	if (doc1.HasParseError())
	{
		cout << "GetParseError%sn" << 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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读