简介
RapidJSON是一个C++的JSON解析器及生成器。它小而全、速度快、独立(不依赖stl、broost)、对内存友好(在大部分32/64位机器上,每个JSON值只占16位(字符串除外)、对Unicode友好(支持UTF-8、UTF-16、UTF-32)。且跨平台(支持Windows.Cygwin.MacOS.iOS.Android)
安装
只有头文件的C++库,只需要把include/rapidjson目录复制到系统或项目的include目录中。
使用
1.Value及Document
每个JSON值都存储为Value类,而Document类则表示整个DOM,它存储了一个DOM树的根Value。Rapidjson的所有公共类型及函数都在rapidjson命名空间中。
查询Value
假设json数据为 string json={“hello”:" “world”,“t”:true,“f”:false,“n”:null,“i”:123,“pi”:3.1416,“a”:[1,2,3,4]}
{
“hello”: “world”,
“t”: true ,
“f”: false,
“n”: null,
“i”: 123,
“pi”: 3.1416,
“a”: [1, 2, 3, 4]
}
把它解析到一个Document:
Document document;document.Parse(json);
那么现在该JSON就会被解析到Document中,成为一棵DOM树,
较早的版本中,根值只允许是object({}括起来的) 或Array([]括起来),后来做出更新,根值可以是任何类型。而上述例子根是个Object
assert(document.IsObject());
验证根值是不是对象。
assert(document.HasMember(“hello”));
验证根object中有没有"hello"成员。
assert(document[“hello”].IsString());
验证"hello"成员的值是不是string类型。类似的API有:document[“t”].IsBool();
document[“i”].IsInt();
document[“pi”].IsNumber();
document[“pi”].IsDouble();
对一个String的Value调用GetInt()是非法的。
printf(“hello=s%\n”,document[“hello”].GetString());
获取"hello对象的值"。
类似API有:document[“t”].GetBool();
document[“n”].IsNull();
document[“i”].GetInt();
//另一种方法(int)document[“i”]
document[“pi”].GetDouble();
查询Array
const Value& a=document[“a”];
assert(a.IsArray());
for(SizeType i=0;i<a.Size();i++)//SizeType是unsigned的typedef
int b=a[i].GetInt();
//for(Value::ConstValueIterator iter=a.Begin();iter!=a.End();++iter)
//int b=iter->GetInt();
//for(auto& v:a.GetArray())
//int b=v.GetInt();
查询Object
和 Array 相似,我们可以用迭代器去访问所有 Object 成员:
static const char* kTypeNames[] =
{ “Null”, “False”, “True”, “Object”, “Array”, “String”, “Number” };
for (Value::ConstMemberIterator itr = document.MemberBegin();
itr != document.MemberEnd(); ++itr)
{
printf(“Type of member %s is %s\n”,
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
注意,当 operator[](const char*) 找不到成员,它会断言失败。
若我们不确定一个成员是否存在,便需要在调用 operator[](const char*) 前先调用 HasMember()。然而,这会导致两次查找。更好的做法是调用 FindMember(),它能同时检查成员是否存在并返回它的 Value:
Value::ConstMemberIterator itr = document.FindMember(“hello”);
if (itr != document.MemberEnd())
printf("%s\n", itr->value.GetString());
范围 for 循环 (v1.1.0 中的新功能)
当使用 C++11 功能时,你可使用范围 for 循环去访问 Object 内的所有成员。
for (auto& m : document.GetObject())
printf(“Type of member %s is %s\n”,
m.name.GetString(), kTypeNames[m.value.GetType()]);