rapidjson操作指南

本文将介绍如何用rapidjson的DOM方式进行json的常见操作:


一、读取json数据

代码

const char json[] = " { \"hello\" : \"world\",\"t\" : true,\"f\" : false,\"n\": null,\"i\":123,\"pi\": 3.1416,\"a\":[1,2,3,4] } ";

	Document document;	// Default template parameter uses UTF8 and MemoryPoolAllocator.
	char buffer[sizeof(json)];
	memcpy(buffer,json,sizeof(json));
	if (document.ParseInsitu<0>(buffer).HasParseError()) {
		return 1;
	}

	printf("\nParsing to document succeeded.\n");

	////////////////////////////////////////////////////////////////////////////
	// 2. Access values in document. 

	printf("\nAccess values in document:\n");
	assert(document.IsObject());	// Document is a JSON value represents the root of DOM. Root can be either an object or array.

	assert(document.HasMember("hello"));
	assert(document["hello"].Isstring());
	printf("hello = %s\n",document["hello"].GetString());

	assert(document["t"].IsBool());		// JSON true/false are bool. Can also uses more specific function IsTrue().
	printf("t = %s\n",document["t"].GetBool() ? "true" : "false");

	assert(document["f"].IsBool());
	printf("f = %s\n",document["f"].GetBool() ? "true" : "false");

	printf("n = %s\n",document["n"].IsNull() ? "null" : "?");

	assert(document["i"].IsNumber());	// Number is a JSON type,but C++ needs more specific type.
	assert(document["i"].IsInt());		// In this case,IsUint()/IsInt64()/IsUInt64() also return true.
	printf("i = %d\n",document["i"].GetInt());	// Alternative (int)document["i"]

	assert(document["pi"].IsNumber());
	assert(document["pi"].IsDouble());
	printf("pi = %g\n",document["pi"].GetDouble());

	{
		const Value& a = document["a"];	// Using a reference for consecutive access is handy and faster.
		assert(a.IsArray());
		for (SizeType i = 0; i < a.Size(); i++)	// rapidjson uses SizeType instead of size_t.
			printf("a[%d] = %d\n",i,a[i].GetInt());
		
		// Note:
		//int x = a[0].GetInt();					// Error: operator[ is ambiguous,as 0 also mean a null pointer of const char* type.
		int y = a[SizeType(0)].GetInt();			// Cast to SizeType will work.
		int z = a[0u].GetInt();						// This works too.
	}

	system("pause");

运行结果:



Parsing to document succeeded.


Access values in document:
hello = world
t = true
f = false
n = null
i = 123
pi = 3.1416
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
请按任意键继续. . .


二,构造json数据

Document变量被声明之后,要先调用Setobject方法

如果Document中没有某个字段,那么要先调用addmember增加这个字段,才可以往里面赋值

向array中增加字段时,要传入allocator

给某个字段赋予字符串时,有两种方式,一、只传入字符串的指针,二、将整个字符串拷贝一份进去

const char json[] = " { \"hello\" : \"world\",sizeof(json));
	if (document.ParseInsitu<0>(buffer).HasParseError()) {
		return 1;
	}

	// Adding values to array.
	{
		Value& a = document["a"];	// This time we uses non-const reference.
		Document::AllocatorType& allocator = document.GetAllocator();
		for (int i = 5; i <= 10; i++)
			a.PushBack(i,allocator);	// May look a bit strange,allocator is needed for potentially realloc. We normally uses the document's.

		// Fluent API
		a.PushBack("Lua",allocator).PushBack("Mio",allocator);
	}

	// Making string values.

	// This version of SetString() just store the pointer to the string.
	// So it is for literal and string that exists within value's life-cycle.
	{
		document["hello"] = "rapidjson";	// This will invoke strlen()
		// Faster version:
		// document["hello"].SetString("rapidjson",9);
	}

	// This version of SetString() needs an allocator,which means it will allocate a new buffer and copy the the string into the buffer.
	Value author;
	{
		char buffer[10];
		int len = sprintf(buffer,"%s %s","Milo","Yip");	// synthetic example of dynamically created string.

		author.SetString(buffer,len,document.GetAllocator());
		// Shorter but slower version:
		// document["hello"].SetString(buffer,document.GetAllocator());

		// Constructor version: 
		// Value author(buffer,document.GetAllocator());
		// Value author(buffer,document.GetAllocator());
		memset(buffer,sizeof(buffer)); // For demonstration purpose.
	}
	// Variable 'buffer' is unusable Now but 'author' has already made a copy.
	document.AddMember("author",author,document.GetAllocator());

	assert(author.IsNull());		// Move semantic for assignment. After this variable is assigned as a member,the variable becomes null.

	////////////////////////////////////////////////////////////////////////////
	// 4. Stringify JSON

	printf("\nModified JSON with reformatting:\n");
	FileStream f(stdout);
	PrettyWriter<FileStream> writer(f);
	document.Accept(writer);	// Accept() traverses the DOM and generates Handler events.

	system("pause");

三、导出json数据

需要调用document的Accept方法,传入一个Writer,Writer可以用文件流或者字符串来构造

导出json数据到文件,这里以导出到stdout为例

FileStream f(stdout);
	PrettyWriter<FileStream> writer(f);
	document.Accept(writer);	// Accept() traverses the DOM and generates Handler events.

导出json数据到字符串,
StringBuffer strbuf;
	Writer<StringBuffer> writer(strbuf);
	document.Accept(writer);

这里的StringBuffer是rapidjson/stringbuffer.h中的类


完毕。。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交互,节省带宽和时间,提高用户体验。在使用AJAX时,需要通过解析JSON格式的数据,来获取所需要的数据。
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面中展示出来。其中,JSON是一种常用的数据格式。那么,在使用Ajax获取JSON数据后,如何将数据取出来呢?
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用AJAX技术可以在不刷新页面的情况下异步获取数据。那么我们该如何循环JSON对象数组呢?下面我们通过一段代码来进行讲解。
AJAX(Asynchronous JavaScript and XML)是一种用于创建 Web 应用程序的技术,它使用 JavaScript 和 XML(或 JSON)来在后台异步传输数据。
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面的情况下,向服务器发出请求并更新页面,实现了异步更新的效果。而传递JSON数据是AJAX中比较常见的一种方法,下面是如何使用AJAX传递JSON数据的详细介绍。
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无需刷新页面的异步数据交互。在处理数据时,常常需要删除一些已存在的数据。本文将介绍如何使用Ajax删除JSON数据库中的数据。
在使用Ajax时,我们经常需要将数据格式化为JSON格式。JSON是一种轻量级数据交换格式,它以键值对的形式来表达数据。
AJAX是一种支持异步请求的技术,它可以让前端页面不用刷新就能向后台请求数据,并异步地展示给用户,提高了用户的体验感。其中,使用JSON格式化数据可以帮助我们更方便快捷地处理返回的数据。
AJAX是一种前端技术,可以通过异步请求来获取数据,并在页面上更新它们。JSON是一种轻量级的数据交换格式,因为它易于读取和编写,因此在Web应用程序中被广泛使用。AJAX传送JSON数据是一种常见的技术,可以让Web应用
在前端开发中,ajax是很常见的技术,它可以在不刷新整个页面的情况下请求服务器数据和更新部分页面。而当需要遍历多个json文件时,可以使用ajax循环遍历来实现。
AJAX技术是实现Web页面无刷新的最佳方式。其中json解析是一种常用的技术,它可以通过AJAX异步请求数据,再用json解析器将返回的json字符串解析成JavaScript对象。下面就让我们来看看如何使用ajax解析json数据。
AJAX技术可以在不刷新整个WEB页面的情况下与服务器进行数据交换,这使得在现代WEB应用中使用AJAX技术变得非常普遍。而访问JSON数组是一种非常常见的AJAX操作。在本文中,我们将向您展示如何使用AJAX技术循环遍历JSO
Ajax(Asynchronous JavaScript and XML)是一种在不重新加载整个页面的情况下更新网页的技术。它可以向服务器发送请求并接收响应,然后使用JavaScript动态地显示内容。
AJAX技术可以帮助我们实现对JSON数据库的循环读取。下面我们来介绍一下如何使用AJAX技术读取JSON数据库。
AJAX是一种在Web应用中实现局部更新的技术。而JSON是一种数据格式,非常适合用来表示数据。在AJAX中,我们经常需要从后端服务器获取JSON格式的数据,在前端页面中进行处理。那么,如何解析JSON数据呢?
AJAX是一种在不重新载入整个页面的情况下,能够更新部分页面的技术,它可以通过异步通信获取后台数据,其中JSON作为一种轻量级数据交换格式,常常被用来传递数据。在使用AJAX接收到后台传送的JSON数据后,需要进行解
在网站开发中,为了减少页面的刷新,异步加载技术成为了开发中越来越常见的一种技术,而 AJAX 技术就是一种常见的实现方式。其中,通过循环读取 JSON 数据能够实现页面内容的实时更新。
在前端开发中,经常需要从服务器获取JSON数据来展示在页面上,而循环遍历这些数据就需要使用AJAX以及JavaScript。本文将介绍如何使用AJAX和JavaScript来循环遍历JSON数据。
在前端开发中,我们常常需要通过 Ajax 请求后端接口获取数据并进行展示。而 JSON 数据则是一种常见的数据格式,因此我们需要了解如何通过 Ajax 获取 JSON 数据。
在使用ajax传递数据时,我们通常会遇到传递json数据类型的情况。那么,接下来我们就来仔细了解一下如何使用ajax传递json数据类型。