本节主要介绍RapidJson是如何使用的。

  (1)RapidJson是什么

RapidJson是一个跨平台的c++的json的解析器和生成器;
相比较jsoncpp库,RapidJson只有头文件,容易安装;
RapidJSON 不依赖STL和boost等外部库独立;
只使用如下文件:<cstdio>, <cstdlib>, <cstring>, <inttypes.h>, <new>, <stdint.h>;
高性能,使用模版及内联函数去降低函数调用开销、内部经优化的 Grisu2 及浮点数解析实现、可选的 SSE2/SSE4.2 支持.

  (2)RapidJson使用范例(DOM解析json字符串并修改json中指定元素的值)

#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h" using namespace std;
using namespace rapidjson; int main(int argv ,char *argc[])
{
//1.把JSON解析至DOM
const char * strJson = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":100}";
Document doc;
doc.Parse(strJson);
cout<< strJson << endl;
//2.利用DOM作出修改
Value& v1 = doc["key2"];
v1="value_modify";
//v1.SetString("value_modify");
Value& v2 = doc["key3"];
v2.SetInt(v2.GetInt()+);
//SetString()
//SetBool()
//SetUint()
//SetInt64()
//SetUInt64()
//SetDouble()
//SetFloat()
//SetArray()
//SetObject()
//SetNull() //3.将DOM stringfy 为json
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
doc.Accept(writer); cout<< buffer.GetString() << endl;
return ;
}
{"key1":"value1","key2":"value2","key3":}
{"key1":"value1","key2":"value_modify","key3":}

  (3)文件对象模型(Document Object Model, DOM)API

文件对象模型,在RapidJson中广泛的使用。

    1.构建json value到DOM:

#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h" using namespace std;
using namespace rapidjson; int main(int argv ,char *argc[])
{
// 1.准备数据
string name = "MenAngel";
string gender = "boy";
int age = ;
vector<string> hobbys = {"语文","数学","英语"};
map<string,double> score ={{"语文",},{"数学",},{"英语",}}; // 2.初始化DOM
StringBuffer strBuffer;
Writer<StringBuffer> writer(strBuffer);
//2.1 根DOM开始
writer.StartObject();
writer.Key("name");
writer.String(name.c_str());
writer.Key("gender");
writer.String(gender.c_str());
writer.Key("age");
writer.Int(age);
writer.Key("hobby");
writer.StartArray();
for(auto &item : hobbys)
{
writer.String(item.c_str());
}
writer.EndArray();
writer.Key("scores");
writer.StartObject();
for(auto &item : scores)
{
writer.Key((item.first).c_str());
writer.Double(item.second);
}
writer.EndObject();
//2.2 根DOM结束
writer.EndObject(); //3.将上述DOM组织的json数据写入json.txt文件
string outFileName = "json.txt";
ofstream outfile(outFileName,std::ios::trunc);
outfile<<strBuffer.GetString()<<endl;
outfile.flush();
outfile.close();
return ;
}
{"name":"MenAngel","gender":"boy","age":23,"hobbys":["语文","数学","英语"],"scores":{"数学":90.0,"英语":100.0,"语文":80.0}}

    2.构建Json Value到DOM

#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h" using namespace std;
using namespace rapidjson; int main(int argv ,char *argc[])
{
// 1.准备数据
string name = "MenAngel";
string gender = "boy";
int age = ;
vector<string> hobbys = {"语文","数学","英语"};
map<string,double> scores ={{"语文",},{"数学",},{"英语",}}; //2.初始化DOM
Document doc;
Document::AllocatorType& allocator = doc.GetAllocator();
doc.SetObject();//实例化一个GenericValue到根DOM
Value tempValue1;
tempValue1.SetString(name.c_str(),allocator);
doc.AddMember("name",tempValue1,allocator);
Value tempValue2(rapidjson::kObjectType);
tempValue2.SetString(gender.c_str(),allocator);
doc.AddMember("gender",tempValue2,allocator);
doc.AddMember("age",age,allocator);
Value tempValue3(kArrayType);
for(auto hobby:hobbys)
{
Value hobbyValue(kStringType);
hobbyValue.SetString(hobby.c_str(),allocator);
tempValue3.PushBack(hobbyValue,allocator);
}
doc.AddMember("hobbys",tempValue3,allocator);
Value tempValue4(kObjectType);
tempValue4.SetObject();
for(auto score : scores)
{
Value scoreValue(kNumberType);
//cout<<score.second;
scoreValue.SetInt(score.second);
Value scoreName(kStringType);
scoreName.SetString(score.first.c_str(),allocator);
tempValue4.AddMember(scoreName,scoreValue,allocator);
}
doc.AddMember("scores",tempValue4,allocator);
StringBuffer strBuffer;
Writer<StringBuffer> writer(strBuffer);
doc.Accept(writer); string outFileName = "json.txt";
ofstream outfile(outFileName,std::ios::trunc);
outfile<<strBuffer.GetString()<<endl;
outfile.flush();
outfile.close();
return ;
}
{"name":"MenAngel","gender":"boy","age":,"hobbys":["语文","数学","英语"],"scores":{"数学":90.0,"英语":100.0,"语文":80.0}}

    3.RapidJSon查询

#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace std;
using namespace rapidjson; int main(int argv,char *argc[])
{
//1.构建json
const char * strJson = "{\"name\":\"MenAngel\",\"age\":23,\"hobbys\":[\"语文\",\"数学\",\"英语\"]}";
Document doc;
doc.Parse(strJson);
StringBuffer strBuffer;
Writer<StringBuffer> writer(strBuffer);
doc.Accept(writer);
cout<<strBuffer.GetString()<<endl;
//2.查询json值
cout<<"遍历方法一:"<<endl;
int count = doc.MemberCount();
cout<<"doc 的属性成员有 "<<count<<"个!"<<endl;
static const char* kTypeNames[] =
{ "Null", "False", "True", "Object", "Array", "String", "Number" };
int i = ;
for(Value::MemberIterator iter = doc.MemberBegin();iter != doc.MemberEnd();++iter)
{
cout<<++i<<".property "<<iter->name.GetString()<<" is "<<kTypeNames[iter->value.GetType()]<<endl;
if(iter->value.GetType() == )
{
//3.遍历Array
for(auto &item : iter->value.GetArray())
//IsBool、IsObject、IsInt、IsNull、IsNumber、IsDouble
if(item.IsString())
cout<<"item = "<<item.GetString()<<endl;
}
}
//4.查询某个成员是否存在
Value::ConstMemberIterator it = doc.FindMember("scores");
if(it != doc.MemberEnd())
cout<<"Has Finded!"<<endl;
else
cout<<"Not Finded!"<<endl;
//5.遍历doc的所有成员
cout<<"遍历方法二:"<<endl;
for(auto &m :doc.GetObject())
{
cout<<"Has member :"<<m.name.GetString()<<" = ";
if(m.value.IsString())
cout<<m.value.GetString()<<endl;
if(m.value.IsInt())
cout<<m.value.GetInt()<<endl;
if(m.value.IsBool())
cout<<m.value.GetBool()<<endl;
if(m.value.IsArray())
cout<<"is array"<<endl;
}
return ;
}
{"name":"MenAngel","age":,"hobbys":["语文","数学","英语"]}
遍历方法一:
doc 的属性成员有 3个!
.property name is String
.property age is Number
.property hobbys is Array
item = 语文
item = 数学
item = 英语
Not Finded!
遍历方法二:
Has member :name = MenAngel
Has member :age =
Has member :hobbys = is array

    4.RapidJson属性获取

#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace std;
using namespace rapidjson; int main(int argv,char *argc[])
{
//1.构建json
const char * strJson = "{\"name\":\"MenAngel\",\"age\":23,\"hobbys\":[\"语文\",\"数学\",\"英语\"]}";
Document doc;
doc.Parse(strJson);
StringBuffer strBuffer;
Writer<StringBuffer> writer(strBuffer);
doc.Accept(writer);
cout<<strBuffer.GetString()<<endl;
//2.DOM根是一个对象
if(doc.IsObject())
cout<<"doc is object!"<<endl;
//3.doc不为j空
if(!doc.IsNull())
{
cout<<"doc is not null!"<<endl;
}
Document document;
if(document.IsNull())
{
cout<<"document is null!"<<endl;
cout<<"Set Object"<<endl;
document.SetObject();
}
if(!document.IsNull())
cout<<"document is not null!"<<endl;
//4.DOM 的大小.
cout<<"doc.MemmberCount() = "<<doc.MemberCount()<<endl;
//5.增加HasMember判断防止断言错误
if(doc.HasMember("hobbys") && !doc["hobbys"].Empty())
cout<<"doc[\"hobbys\"] is not empty!"<<endl;
else
cout<<"member not exits!"<<endl;
//6.取键值
Value::ConstMemberIterator iter = doc.FindMember("age");
if(iter != doc.MemberEnd())
{
cout<<"Member age is exits!"<<endl;
cout<<iter->name.GetString()<<":"<<iter->value.GetInt()<<endl;
}
//7.Array的大小
cout<<"doc[\"hobbys\"].Capacity() = "<<doc["hobbys"].Capacity()<<endl;
//8.字符串的大小 当字符中存在\u0000时strlen会到此截断
cout<<"doc[\"name\"].length = "<<strlen(doc["name"].GetString())<<endl;
cout<<"doc[\"name\"].length = "<<doc["name"].GetStringLength()<<endl;
doc.AddMember("test","a\u0000b",doc.GetAllocator());
//只能当test成员存在时才能直接赋值
//doc["test"] = "a\u0000b";
cout<<"doc[\"test\"].length = "<<strlen(doc["test"].GetString())<<endl;
cout<<"doc[\"test\"].length = "<<doc["test"].GetStringLength()<<endl;
//
return ;
}
{"name":"MenAngel","age":,"hobbys":["语文","数学","英语"]}
doc is object!
doc is not null!
document is null!
Set Object
document is not null!
doc.MemmberCount() =
doc["hobbys"] is not empty!
Member age is exits!
age:
doc["hobbys"].Capacity() =
doc["name"].length =
doc["name"].length =
doc["test"].length =
doc["test"].length =

    5.RapidJson一些特性

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace std;
using namespace rapidjson; int main(int argv,char *argc[])
{
//1.构建json
const char * strJson = "{\"name\":\"MenAngel\",\"age\":23,\"hobbys\":[\"语文\",\"数学\",\"英语\"]}";
Document doc;
doc.Parse(strJson);
StringBuffer strBuffer;
Writer<StringBuffer> writer(strBuffer);
doc.Accept(writer);
cout<<strBuffer.GetString()<<endl;
//2.const char *、string、value(kStringType)之间比较大小
if(doc["name"] == "MenAngel")
cout<<"(1)doc[\"name\"] equal MenAngel!"<<endl;
if(doc["name"].GetString() == string("MenAngel"))
cout<<"(2)doc[\"name\"] equal MenAngel!"<<endl;
if( == strcmp(doc["name"].GetString(),"MenAngel"))
cout<<"(3)doc[\"name\"] equal MenAngel!"<<endl;
if(doc["name"].GetString() != "MenAngel")
cout<<"(4)不成立!"<<endl;
//3.value赋值
Value v;//v is NULL && v is not Object
if(v.IsNull())
cout<<"v is Null()"<<endl;
v.SetObject();
if(v.IsObject())
cout<<"v is Object"<<endl;
Value tValue(kObjectType);//tValue is not Null,tValue is Object
if(!tValue.IsNull())
cout<<"tVlaue is not NULL!"<<endl;
if(tValue.IsObject())
cout<<"tValue is Object"<<endl;
//4.转移语义,避免value深赋值
//AddMember(), PushBack()、赋值均采用深赋值
Value a();
Value b();
a = b;
if(b.IsNull())
cout<<"b is Null,"<<"a = "<<a.GetInt()<<endl;
Value c(kArrayType);
Document::AllocatorType& allocator = doc.GetAllocator();
c.PushBack(Value(), allocator);
c.PushBack(Value().SetInt(), allocator); // fluent API
c.PushBack(Value().Move(), allocator); // 转移语义
cout<<"c.Capacity() = "<<c.Capacity()<<endl;
cout<<"c.Size() = "<<c.Size()<<endl;
for(auto &m : c.GetArray())
{
cout<<"item = "<<m.GetInt()<<endl;
}
//字符串的容量及大小
cout<<"doc[\"hobbys\"].Size() = "<<doc["hobbys"].Size()<<endl;
cout<<"doc[\"hobbys\"].Capacity() = "<<doc["hobbys"].Capacity()<<endl;
//5.交换value
Value d();
Value e("string");
d.Swap(e);
if(!d.IsNull() && !e.IsNull())
{
cout<<"d is not null,e is not null!"<<endl;
cout<<"d = "<<d.GetString()<<" e = "<<e.GetInt()<<endl;
}
//6.创建string
//复制字符串
Value f(kStringType);
char str[] = "My first string!";
f.SetString(str,doc.GetAllocator());
cout<<f.GetString()<<endl;
Value g;
char buffer[];
int len = sprintf(buffer, "%s -> %s", "name", "value"); // 动态创建的字符串。
g.SetString(buffer,len,doc.GetAllocator());
//g.SetString(buffer,doc.GetAllocator())
cout<<g.GetString()<<endl;
//简单引用常量字符串
Value h;
h.SetString("My third String!");// h = "My thrid String!"
cout<<h.GetString()<<endl;
//简单引用常量l字符串
Value i;
const char * tempStr = "my fourth string";
size_t cstr_len = strlen(tempStr);
i.SetString(StringRef(tempStr));
//i.SetString(StringRef(tempStr,cstr_len));
//i = StringRef(tempStr,cstr_len)
//i = StringRef(tempStr)
//i.SetString(tempStr); 不合法
cout<<i.GetString()<<endl;
return ;
}
{"name":"MenAngel","age":,"hobbys":["语文","数学","英语"]}
()doc["name"] equal MenAngel!
()doc["name"] equal MenAngel!
()doc["name"] equal MenAngel!
()不成立!
v is Null()
v is Object
tVlaue is not NULL!
tValue is Object
b is Null,a =
c.Capacity() =
c.Size() =
item =
item =
item =
doc["hobbys"].Size() =
doc["hobbys"].Capacity() =
d is not null,e is not null!
d = string e =
My first string!
name -> value
My third String!
my fourth string

(2)RapidJson的详解及使用的更多相关文章

  1. Linq之旅:Linq入门详解(Linq to Objects)

    示例代码下载:Linq之旅:Linq入门详解(Linq to Objects) 本博文详细介绍 .NET 3.5 中引入的重要功能:Language Integrated Query(LINQ,语言集 ...

  2. 架构设计:远程调用服务架构设计及zookeeper技术详解(下篇)

    一.下篇开头的废话 终于开写下篇了,这也是我写远程调用框架的第三篇文章,前两篇都被博客园作为[编辑推荐]的文章,很兴奋哦,嘿嘿~~~~,本人是个很臭美的人,一定得要截图为证: 今天是2014年的第一天 ...

  3. EntityFramework Core 1.1 Add、Attach、Update、Remove方法如何高效使用详解

    前言 我比较喜欢安静,大概和我喜欢研究和琢磨技术原因相关吧,刚好到了元旦节,这几天可以好好学习下EF Core,同时在项目当中用到EF Core,借此机会给予比较深入的理解,这里我们只讲解和EF 6. ...

  4. Java 字符串格式化详解

    Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...

  5. Android Notification 详解(一)——基本操作

    Android Notification 详解(一)--基本操作 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Notification 文中如有纰 ...

  6. Android Notification 详解——基本操作

    Android Notification 详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 前几天项目中有用到 Android 通知相关的内容,索性把 Android Notificatio ...

  7. Git初探--笔记整理和Git命令详解

    几个重要的概念 首先先明确几个概念: WorkPlace : 工作区 Index: 暂存区 Repository: 本地仓库/版本库 Remote: 远程仓库 当在Remote(如Github)上面c ...

  8. Drawable实战解析:Android XML shape 标签使用详解(apk瘦身,减少内存好帮手)

    Android XML shape 标签使用详解   一个android开发者肯定懂得使用 xml 定义一个 Drawable,比如定义一个 rect 或者 circle 作为一个 View 的背景. ...

  9. Node.js npm 详解

    一.npm简介 安装npm请阅读我之前的文章Hello Node中npm安装那一部分,不过只介绍了linux平台,如果是其它平台,有前辈写了更加详细的介绍. npm的全称:Node Package M ...

随机推荐

  1. 第一次亲密接触——二狗子初识 CDN

    二狗子是国内知名XXX大学的在校学生,作为一名编程爱好者,他利用业余时间搭建了一个网站,把平时的学习心得和技术分享全都 PO 在自己的网站上.渐渐地,二狗子的网站因为文章质量高,技术分享全面,受到了很 ...

  2. ASP.NET CORE 2.* 利用集成测试框架覆盖HttpClient相关代码

    ASP.NET CORE 集成测试官方介绍 我的asp.net core 项目里面大部分功能都是去调用别人的API ,大量使用HttpClient,公司单元测试覆盖率要求95%以上,很难做到不mock ...

  3. ES6中。类与继承的方法,以及与ES5中的方法的对比

    // 在ES5中,通常使用构造函数方法去实现类与继承 // 创建父类 function Father(name, age){ this.name = name; this.age = age; } F ...

  4. Kubernetes-保障集群内节点和网络安全

    13.1.在pod中使用宿主节点的Linux命名空间 13.1.1.在pod中使用宿主节点的网络命名空间 在pod的yaml文件中就设置spec.hostNetwork: true 这个时候pod使用 ...

  5. 6.PHP操作MySQL的步骤

    第一步:PHP连接MySQL服务器 第三步:设置MySQL请求或返回数据的字符集 第四步:执行各种SQL语句 l 查询SQL语句:mysql_query(“SELECT * FROM 007_news ...

  6. Luogu P5490 扫描线

    模板题,想象一条线从左边扫到右边,只有在矩阵边界才会产生影响,所以我们离散化缩小数据范围,再用线段树维护扫描线上的情况,得出结果 #include<bits/stdc++.h> #defi ...

  7. idea + springboot 的java后台服务器通过小米推送

    public class XiaomiPush { // 1.小米推送(我只推送Android且只应用regId发起推送,所以下面只有推送Android的代码 private static final ...

  8. 解决mysql乱码

    总结的几个乱码问题 希望我们全体学员也能够学会总结 java web 很是希望大家能够学好.并且也希望大家能够在学习过程中不段的积累相关的知识点 1.在response中写<meta  http ...

  9. c++ 左移

    maxval = (1 << d) - 1: d=8 意思是2^d-1,相当于1左移d位

  10. egret之弹幕

    要实现弹幕功能,首先需要将弹幕配置成配置表.然后代码随机生成. /**生成单个弹幕 */ private showCaptionAnim(captionText: string) { egret.lo ...