转自:https://blog.csdn.net/qq849635649/article/details/52678822

我在工作中一直使用的是rapidjson库,这是我在工作中使用该库作的一些整理,以读写下面的这段json字符串为例来进行整理,该字符串覆盖了平时使用的布尔类型、整型、浮点类型、结构体类型、字符串类型以及相对应的数组类型。

代码地址:https://git.oschina.net/zhaoyf/zhaoyf_csdn/tree/master/test_json

这时生成的目标json字符串

{
"Int": 1,
"Double": 12.0000001,
"String": "This is a string",
"Object": {
"name": "qq849635649",
"age": 25
},
"IntArray": [
10,
20,
30
],
"DoubleArray": [
1,
2,
3
],
"StringArray": [
"one",
"two",
"three"
],
"MixedArray": [
"one",
50,
false,
12.005
],
"People": [
{
"name": "qq849635649",
"age": 0,
"sex": true
},
{
"name": "qq849635649",
"age": 10,
"sex": false
},
{
"name": "qq849635649",
"age": 20,
"sex": true
}
]
}

一、写json协议

1. 下面这段代码是我最喜欢用的一种方式,使用字符串缓冲器生成

 #include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include <iostream>
#include <string> using namespace std; void Serialize_1()
{
rapidjson::StringBuffer strBuf;
rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf); writer.StartObject(); //1. 整数类型
writer.Key("Int");
writer.Int(); //2. 浮点类型
writer.Key("Double");
writer.Double(12.0000001); //3. 字符串类型
writer.Key("String");
writer.String("This is a string"); //4. 结构体类型
writer.Key("Object");
writer.StartObject();
writer.Key("name");
writer.String("qq849635649");
writer.Key("age");
writer.Int();
writer.EndObject(); //5. 数组类型
//5.1 整型数组
writer.Key("IntArray");
writer.StartArray();
//顺序写入即可
writer.Int();
writer.Int();
writer.Int();
writer.EndArray(); //5.2 浮点型数组
writer.Key("DoubleArray");
writer.StartArray();
for(int i = ; i < ; i++)
{
writer.Double(i * 1.0);
}
writer.EndArray(); //5.3 字符串数组
writer.Key("StringArray");
writer.StartArray();
writer.String("one");
writer.String("two");
writer.String("three");
writer.EndArray(); //5.4 混合型数组
//这说明了,一个json数组内容是不限制类型的
writer.Key("MixedArray");
writer.StartArray();
writer.String("one");
writer.Int();
writer.Bool(false);
writer.Double(12.005);
writer.EndArray(); //5.5 结构体数组
writer.Key("People");
writer.StartArray();
for(int i = ; i < ; i++)
{
writer.StartObject();
writer.Key("name");
writer.String("qq849635649");
writer.Key("age");
writer.Int(i * );
writer.Key("sex");
writer.Bool((i % ) == );
writer.EndObject();
}
writer.EndArray(); writer.EndObject(); string data = strBuf.GetString();
cout << data << endl;
}

2. 接下来这种方式是我刚开始学习使用该库时网上收到的结果,使用不像上面那么方便

 #include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h" void Serialize_2()
{
rapidjson::Document doc;
doc.SetObject();
rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); //1. 整型类型
doc.AddMember("Int", , allocator); //2. 浮点类型
doc.AddMember("Double", 12.00001, allocator); //3. 字符串类型
//正确方式
string str= "This is a string";
rapidjson::Value str_value(rapidjson::kStringType);
str_value.SetString(str.c_str(), str.size());
if(!str_value.IsNull())
{
doc.AddMember("String", str_value, allocator);
}
/**
* 注:以下方式不正确,可能成功,也可能失败,因为字符串写入json要重新开辟内存,
* 如果使用该方式的话,当数据是字符串常量的话是没问题的,如果为变量就会显示乱码,所
* 以为保险起见,我们显式的分配内存(无需释放)
*/
//doc.AddMember("String", str.data(), allocator); //4. 结构体类型
rapidjson::Value object(rapidjson::kObjectType);
object.AddMember("name", "qq849635649", allocator); //注:常量是没有问题的
object.AddMember("age", , allocator);
doc.AddMember("Object", object, allocator); //5. 数组类型
//5.1 整型数组
rapidjson::Value IntArray(rapidjson::kArrayType);
IntArray.PushBack(, allocator);
IntArray.PushBack(, allocator);
IntArray.PushBack(, allocator);
doc.AddMember("IntArray", IntArray, allocator); //5.2 浮点型数组
rapidjson::Value DoubleArray(rapidjson::kArrayType);
DoubleArray.PushBack(1.0, allocator);
DoubleArray.PushBack(2.0, allocator);
DoubleArray.PushBack(3.0, allocator);
doc.AddMember("DoubleArray", DoubleArray, allocator); //5.3 字符型数组
rapidjson::Value StringArray(rapidjson::kArrayType);
string strValue1 = "one";
string strValue2 = "two";
string strValue3 = "three";
str_value.SetString(strValue1.c_str(), strValue1.size());
StringArray.PushBack(str_value, allocator);
str_value.SetString(strValue2.c_str(), strValue2.size());
StringArray.PushBack(str_value, allocator);
str_value.SetString(strValue3.c_str(), strValue3.size());
StringArray.PushBack(str_value, allocator);
doc.AddMember("StringArray", StringArray, allocator); //5.4 结构体数组
rapidjson::Value ObjectArray(rapidjson::kArrayType);
for(int i = ; i < ; i++)
{
rapidjson::Value obj(rapidjson::kObjectType);
obj.AddMember("name", "qq849635649", allocator);//注:常量是没有问题的
obj.AddMember("age", i * , allocator);
ObjectArray.PushBack(obj, allocator);
}
doc.AddMember("ObjectArray", ObjectArray, allocator); rapidjson::StringBuffer strBuf;
rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf);
doc.Accept(writer); string data = strBuf.GetString();
cout << data << endl;
}

下面是解析的代码,同样的,采用的依旧上面那个json字符串,分门别类的已经整理好

 #include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h" string data =
"{\"Int\":1,"
"\"Double\":12.0000001,"
"\"String\":\"This is a string\","
"\"Object\":{\"name\":\"qq849635649\",\"age\":25},"
"\"IntArray\":[10,20,30],"
"\"DoubleArray\":[1.0,2.0,3.0],"
"\"StringArray\":[\"one\",\"two\",\"three\"],"
"\"MixedArray\":[\"one\",50,false,12.005],"
"\"People\":[{\"name\":\"qq849635649\",\"age\":0,\"sex\":true},"
"{\"name\":\"qq849635649\",\"age\":10,\"sex\":false},"
"{\"name\":\"qq849635649\",\"age\":20,\"sex\":true}]}"; void parse() {
//创建解析对象
rapidjson::Document doc;
//首先进行解析,没有解析错误才能进行具体字段的解析
if(!doc.Parse(data.data()).HasParseError())
{
//1. 解析整数
if(doc.HasMember("Int") && doc["Int"].IsInt())
{
cout << "Int = " << doc["Int"].GetInt() << endl;
}
//2. 解析浮点型
if(doc.HasMember("Double") && doc["Double"].IsDouble())
{
cout << "Double = " << doc["Double"].GetDouble() << endl;
}
//3. 解析字符串
if(doc.HasMember("String") && doc["String"].IsString())
{
cout << "String = " << doc["String"].GetString() << endl;
}
//4. 解析结构体
if(doc.HasMember("Object") && doc["Object"].IsObject())
{
const rapidjson::Value& object = doc["Object"];
if(object.HasMember("name") && object["name"].IsString())
{
cout << "Object.name = " << object["name"].GetString() << endl;
}
if(object.HasMember("age") && object["age"].IsInt())
{
cout << "Object.age = " << object["age"].GetInt() << endl;
}
}
//5. 解析数组类型
//5.1 整型数组类型
if(doc.HasMember("IntArray") && doc["IntArray"].IsArray())
{
//5.1.1 将字段转换成为rapidjson::Value类型
const rapidjson::Value& array = doc["IntArray"];
//5.1.2 获取数组长度
size_t len = array.Size();
//5.1.3 根据下标遍历,注意将元素转换为相应类型,即需要调用GetInt()
for(size_t i = ; i < len; i++)
{
cout << "IntArray[" << i << "] = " << array[i].GetInt() << endl;
}
}
//5.2 浮点型数组类型
if(doc.HasMember("DoubleArray") && doc["DoubleArray"].IsArray())
{
const rapidjson::Value& array = doc["DoubleArray"];
size_t len = array.Size();
for(size_t i = ; i < len; i++)
{
//为防止类型不匹配,一般会添加类型校验
if(array[i].IsDouble())
{
cout << "DoubleArray[" << i << "] = " << array[i].GetDouble() << endl;
}
}
}
//5.3 字符串数组类型
if(doc.HasMember("StringArray") && doc["StringArray"].IsArray())
{
const rapidjson::Value& array = doc["StringArray"];
size_t len = array.Size();
for(size_t i = ; i < len; i++)
{
//为防止类型不匹配,一般会添加类型校验
if(array[i].IsString())
{
cout << "StringArray[" << i << "] = " << array[i].GetString() << endl;
}
}
}
//5.4 混合型
if(doc.HasMember("MixedArray") && doc["MixedArray"].IsArray())
{
const rapidjson::Value& array = doc["MixedArray"];
size_t len = array.Size();
for(size_t i = ; i < len; i++)
{
//为防止类型不匹配,一般会添加类型校验
if(array[i].IsString())
{
cout << "MixedArray[" << i << "] = " << array[i].GetString() << endl;
}
else if(array[i].IsBool())
{
cout << "MixedArray[" << i << "] = " << array[i].GetBool() << endl;
}
else if(array[i].IsInt())
{
cout << "MixedArray[" << i << "] = " << array[i].GetInt() << endl;
}
else if(array[i].IsDouble())
{
cout << "MixedArray[" << i << "] = " << array[i].GetDouble() << endl;
}
}
}
//5.5 结构体数组类型
if(doc.HasMember("People") && doc["People"].IsArray())
{
const rapidjson::Value& array = doc["People"];
size_t len = array.Size();
for(size_t i = ; i < len; i++)
{
const rapidjson::Value& object = array[i];
//为防止类型不匹配,一般会添加类型校验
if(object.IsObject())
{
cout << "ObjectArray[" << i << "]: ";
if(object.HasMember("name") && object["name"].IsString())
{
cout << "name=" << object["name"].GetString();
}
if(object.HasMember("age") && object["age"].IsInt())
{
cout << ", age=" << object["age"].GetInt();
}
if(object.HasMember("sex") && object["sex"].IsBool())
{
cout << ", sex=" << (object["sex"].GetBool() ? "男" : "女") << endl;
}
}
}
}
}
/**
* 最后注意:因为rapidjson不会做安全校验,所以要自己做安全校验,以int整型为例
* “if(object.HasMember("age") && object["age"].IsInt()) {}”
* 这句校验很重要,既要校验有该子段,也要校验类型正确,否则会引发程序崩溃
*/
}

所有的代码都放在上面了,我想不用解释太多,代码浅显易懂,不懂的话可以回复评论。

rapidjson库的基本使用的更多相关文章

  1. 基于RapidJSON的操作库

    需要安装配置RapidJSON库 /******************************************************************* * summery: 提供便 ...

  2. Cocos2d-x移植到WindowsPhone8移植问题-libcurl库移植问题

    在Cocos2d-x 3.x最新版本中提供了Windows Phone 8平台移植libcurl库所需要的头文件和库文件.但要在Windows Phone 8平台成功移植libcurl库还是很不容易, ...

  3. cocos2d-x3.x使用rapidjson

    rapidjson效率高,所以之前cocostudio里面解析用的jsoncpp也换成了rapidjson. 引擎又带有rapidjson库,所以不用单独去下载,直接就可以用. 这里主要写一下关于解析 ...

  4. Cocos2d-x 3.0 Json用法 Cocos2d-x xml解析

    Cocos2d-x 3.0 加入了rapidjson库用于json解析.位于external/json下. rapidjson 项目地址:http://code.google.com/p/rapidj ...

  5. cocos2d_x_06_游戏_一个都不能死

    终于效果图: 环境版本号:cocos2d-x-3.3beta0 使用内置的物理引擎 游戏主场景 // // HeroScene.h // 01_cocos2d-x // // Created by b ...

  6. (27)Cocos2d-x 3.0 Json用法

    Cocos2d-x 3.0 加入了rapidjson库用于json解析.位于external/json下. rapidjson 项目地址:http://code.google.com/p/rapidj ...

  7. C++ JSON解析库RapidJSON

    https://github.com/Tencent/rapidjson jsontext.txt { "result" : [ { "face_id" : & ...

  8. 值得推荐的C/C++框架和库

    值得推荐的C/C++框架和库 [本文系外部转贴,原文地址:http://coolshell.info/c/c++/2014/12/13/c-open-project.htm]留作存档 下次造轮子前先看 ...

  9. [转载]C/C++框架和库

    C/C++框架和库 装载自:http://blog.csdn.net/xiaoxiaoyeyaya/article/details/42541419 值得学习的C语言开源项目 Webbench Web ...

随机推荐

  1. SpringBoot详细研究-01基础

    Springboot可以说是当前最火的java框架了,非常适合于"微服务"思路的开发,大幅缩短软件开发周期. 概念 过去Spring充满了配置bean的xml文件,随着spring ...

  2. 【*】单线程的redis为什么吞吐量可以这么大

    一.Redis的高并发和快速原因 1.redis是基于内存的,内存的读写速度非常快: 2.redis是单线程的,省去了很多上下文切换线程的时间: 3.redis使用多路复用技术,可以处理并发的连接.非 ...

  3. 浅谈2-SAT(待续)

    2-SAT问题,其实是一个逻辑互斥问题.做了两道裸题之后仔细想来,和小时候做过的“有两个女生,如果A是女生,那么B一定不是女生.A和C性别相同,求A.B.C三人的性别.”几乎是一样的. 对于这道题我们 ...

  4. 以管理员身份运行CMD

    To complete these procedures, you must be a member of the Administrators group. To start a command p ...

  5. 试图(View)

    试图是通过命名约定与动作方法想关联的.这个动作方法称为Index,控制器名称为Home; 添加试图,试图名与该试图相关联的动作方法的名称一致.

  6. 【BZOJ-2329&2209】括号修复&括号序列 Splay

    2329: [HNOI2011]括号修复 Time Limit: 40 Sec  Memory Limit: 128 MBSubmit: 1007  Solved: 476[Submit][Statu ...

  7. Codeforces Round #373 (Div. 2) C. Efim and Strange Grade 水题

    C. Efim and Strange Grade 题目连接: http://codeforces.com/contest/719/problem/C Description Efim just re ...

  8. OSX下面用ffmpeg抓取桌面以及摄像头推流进行直播

    参考博客 http://blog.chinaunix.net/uid-11344913-id-4665455.html 在osx系统下通过ffmpeg查看设备 ffmpeg -f avfoundati ...

  9. Spring boot整合jsp

    这几天在集中学习Spring boot+Shiro框架,因为之前view层用jsp比较多,所以想在spring boot中配置jsp,但是spring boot官方不推荐使用jsp,因为jsp相对于一 ...

  10. web网页上面调用qq

    <a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=2812415198&site=q ...