rapidjson官方教程
教程
目录
本教程简介文件对象模型(Document Object Model,DOM)API。 如用法一览中所示,可以解析一个JSON至DOM,然后就可以轻松查询及修改DOM,并最终转换回JSON。 Value 及 Document每个JSON值都储存为 查询Value在本节中,我们会使用到 假设我们用C语言的字符串储存一个JSON(
{
"hello":
"world",
"t": true,128)">"f":
false,128)">"n": null,128)">"i": 123,128)">"pi": 3.1416,128)">"a": [1,2,3,4]
}
把它解析至一个
#include "rapidjson/document.h"
using namespace rapidjson;
// ...
Document document;
document.
Parse(json);
那么现在该JSON就会被解析至
教程中的DOM
自从RFC 7159作出更新,合法JSON文件的根可以是任何类型的JSON值。而在较早的RFC 4627中,根值只允许是Object或Array。而在上述例子中,根是一个Object。
assert(document.IsObject());
让我们查询一下根Object中有没有
assert(document.HasMember(
"hello"));
assert(document[
"hello"].IsString());
printf(
"hello = %sn",document[
"hello"].GetString());
world
JSON True/False值是以 "t"].IsBool());
"t = %sn",128)">"t"].GetBool() ?
"true" :
"false");
true
JSON Null值可用 "n = %sn",128)">"n"].IsNull() ?
"null" :
"?");
null
JSON Number类型表示所有数值。然而,C++需要使用更专门的类型。 "i"].IsNumber());
// 在此情况下,IsUint()/IsInt64()/IsUInt64()也会返回 true
"i"].IsInt());
"i = %dn",128)">"i"].GetInt());
// 另一种用法: (int)document["i"]
"pi"].IsNumber());
"pi"].IsDouble());
"pi = %gn",128)">"pi"].GetDouble());
i = 123
pi = 3.1416
JSON Array包含一些元素。 // 使用引用来连续访问,方便之余还更高效。
const
Value& a = document[
"a"];
assert(a.IsArray());
for (
SizeType i = 0; i < a.Size(); i++)
// 使用 SizeType 而不是 size_t
"a[%d] = %dn",i,a[i].GetInt());
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
注意,RapidJSON并不自动转换各种JSON类型。例如,对一个String的Value调用 以下将会讨论有关查询各类型的细节。 查询Array缺省情况下, 你可以用整数字面量访问元素,如 Array与 for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
"%d ",itr->GetInt());
还有一些熟悉的查询函数:
查询Object和Array相似,我们可以用迭代器去访问所有Object成员: static
const
char* kTypeNames[] =
{
"Null", "False",128)">"True",128)">"Object",128)"> "Array",128)">"String",128)">"Number" };
for (Value::ConstMemberIterator itr = document.MemberBegin();
itr != document.MemberEnd(); ++itr)
"Type of member %s is %sn",monospace; min-height:13px; white-space:pre-wrap; word-wrap:break-word; text-indent:-53px; padding-left:53px; padding-bottom:0px; margin:0px">
itr->name.GetString(),kTypeNames[itr->value.GetType()]);
}
Type of member hello is String
Type of member t is True
Type of member f is False
Type of member n is Null
Type of member i is Number
Type of member pi is Number
Type of member a is Array
注意,当 若我们不确定一个成员是否存在,便需要在调用
Value::ConstMemberIterator itr = document.FindMember(
"hello");
if (itr != document.MemberEnd())
"%s %sn",itr->value.GetString());
查询NumberJSON只提供一种数值类型──Number。数字可以是整数或实数。RFC 4627规定数字的范围由解析器指定。 由于C++提供多种整数及浮点数类型,DOM尝试尽量提供最广的范围及良好性能。 当解析一个Number时,它会被存储在DOM之中,成为下列其中一个类型:
当查询一个Number时,你可以检查该数字是否能以目标类型来提取:
注意,一个整数可能用几种类型来提取,而无需转换。例如,一个名为 当要提取Number类型, 查询String除了 根据RFC 4627,JSON String可包含Unicode字符 |