博客搬家,原地址:https://langzi989.github.io/2017/05/27/rapidjson查询操作基本用法/
本系列文章以例子的方式进行呈现。
#include "rapidjson/document.h"
#include <iostream>
int main()
{
const char* test = "{\"num\":123, \"hello\":null, \"type\": \"object\",\"properties\": {\"oid\": {\"type\": \"string\"}, \"username\": {\"type\": \"string\"},\"creid\": {\"type\": \"string\"}},\"required\": [\"oid\", \"username\",\"creid\"]}";
rapidjson::Document document;
//Parse(const char*). 从c-string解析为Document json格式
document.Parse(test);
//GetString().从Document json中取出string
std::cout << "type = " << document["type"].GetString() << std::endl;
/* 函数原型 函数功能
* IsNull() 判断当前键对应的值是不是null
* IsNumber() 判断当前键对应的值是不是number
* IsInt() 判断当前键对应的值是不是int
* IsDouble() 判断当前键对应的值是不是double
* IsString() 判断当前键对应的值是不是string
* IsBool() 判断当前键对应的值是不是bool
* IsArray() 判断当前键对应的值是不是array
* ...
*/
std::cout << "hello is " << (document["hello"].IsNull() ? "null" : "not null") << std::endl;
std::cout << "num is " << (document["num"].IsNumber() ? "number" : "not number") << std::endl;
std::cout << "required is " << (document["required"].IsArray()? "array" : "not array") << std::endl;
/* 访问Array的两种方法
* 1. 通过下标访问 //使用引用来连续访问,方便之余还更高效。
* 2. 通过迭代器访问
* 注意问题
* 1.索引使用SizeType类型,而不是size_t类型,缺省情况下,SizeType是unsigned的typedef
* 2.对于String类型使用GetInt是非法的,这个时候会导致程序崩溃
*/
const rapidjson::Value &a = document["required"];
assert(a.IsArray());
for (rapidjson::SizeType i = 0; i < a.Size(); i++)
std