RapidJSON入门:手把手教入门实例介绍

RapidJSON优点

  • 跨平台
    编译器:Visual Studio、gcc、clang 等
    架构:x86、x64、ARM 等
    操作系统:Windows、Mac OS X、Linux、iOS、Android 等

  • 容易安装
    只有头文件的库。只需把头文件复制至你的项目中。

  • 独立、最小依赖
    不需依赖 STL、BOOST 等。
    只包含 <cstdio>, <cstdlib>, <cstring>, <inttypes.h>, <new>, <stdint.h>。

  • 没使用 C++ 异常、RTTI

  • 高性能
    使用模版及内联函数去降低函数调用开销。
    内部经优化的 Grisu2 及浮点数解析实现。
    可选的 SSE2/SSE4.2 支持。

RapidJSON教程

1、Value 及 Document

每个 JSON 值都储存为 Value 类,一个 Value 类可包含不同类型的值,而 Document 类则表示整个 DOM,它存储了一个 DOM 树的根 Value。
定义一个JSON字符串,把它解析至一个 Document:

#include "rapidjson/document.h"
 
using namespace rapidjson;
 
// ...

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

Document document;
document.Parse(json);
//JSON.parse()
//在接收服务器数据时一般是字符串。
//可以使用 JSON.parse() 将数据转换为 JavaScript 对象。

那么现在该 JSON 就会被解析至 document 中,成为一棵DOM 树:
在这里插入图片描述

2、查询Value

//根是一个 Object,验证它的类型
assert(document.IsObject());



//查询一下根 Object 中有没有 "hello" 成员
//在此例中,"hello" 成员关联到一个 JSON String
assert(document.HasMember("hello"));
assert(document["hello"].IsString());
printf("hello = %s\n", document["hello"].GetString());
//打印结果:world



//JSON True/False 值是以 bool 表示的。
assert(document["t"].IsBool());
printf("t = %s\n", document["t"].GetBool() ? "true" : "false");
//打印结果:true



//JSON Null 值可用 IsNull() 查询。
printf("n = %s\n", document["n"].IsNull() ? "null" : "?");
//打印结果:null



//JSON Number 类型表示所有数值
//然而,C++ 需要使用更专门的类型
assert(document["i"].IsNumber());
assert(document["i"].IsInt());// 在此情况下,IsUint()/IsInt64()/IsUint64() 也会返回 true
printf("i = %d\n", document["i"].GetInt());
//打印结果:i = 123
assert(document["pi"].IsNumber());
assert(document["pi"].IsDouble());
printf("pi = %g\n", document["pi"].GetDouble());
//打印结果:pi = 3.1416



// 使用引用来连续访问,方便之余还更高效。
const Value& a = document["a"];
assert(a.IsArray());
for (SizeType i = 0; i < a.Size(); i++) // 使用 SizeType 而不是 size_t
        printf("a[%d] = %d\n", i, a[i].GetInt());
//打印结果:a[0] = 1
//         a[1] = 2
//         a[2] = 3
//         a[3] = 4



//用迭代器去访问所有 Object 成员:
static const char* kTypeNames[] = 
{
   
    "Null", "False", 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值