本节主要介绍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. egg 自学入门demo分享

    目录 安装 项目 连接数据库 编写model 编写controller 添加路由 2018-08,本文适用于对egg有兴趣想要了解的同学 完整项目代码:https://github.com/NameH ...

  2. 通过注解实现通用导出Excel

    Javaweb开发中数据的导入导出很常见,每次我们都需要写很多代码,所以我就在想能不能写一些通用的方法,之前已经在网上 整理过一些通用的方法,最近在网上看到一位牛人封装的更加简介,自己拿过来整理了一下 ...

  3. 如何在GitHub上删除自己的项目?

    话不多说,直奔主题~ 1.打开GitHub,在主页左边有自己写的库. 2.拿删除第二个库wlh-hub/vue-zsgc为例,点击它,进入下面页面. 3.在导航栏一栏中,找到settings,并点击. ...

  4. Git原理入门简析

    为了获得更好的阅读体验,建议访问原地址:传送门 前言: 之前听过公司大佬分享过 Git 原理之后就想来自己总结一下,最近一忙起来就拖得久了,本来想塞更多的干货,但是不喜欢拖太久,所以先出一版足够入门的 ...

  5. 聊一聊 SpringBoot 自动配置的原理

    解析思路 我们建立好一个SpringBoot的工程后,我们将从启动类,SpringBootApplication开始进行探究. 开始解析 首先我们建立一个 Springboot的工程.找到启动类,我们 ...

  6. Java并发之内存模型(JMM)浅析

    背景 学习Java并发编程,JMM是绕不过的槛.在Java规范里面指出了JMM是一个比较开拓性的尝试,是一种试图定义一个一致的.跨平台的内存模型.JMM的最初目的,就是为了能够支多线程程序设计的,每个 ...

  7. cmd命令行界面运行python脚本显示的中文不正确

    在notepad++中编写了一个脚本(如图一),在cmd命令行界面中运行却发现显示的中文不正确(如图2).图3显示的是cmd界面的默认编码. 解决方案:将脚本的注释语言改为GBK,编码格式改为ANSI ...

  8. maven项目编译通过,测试用例卡住,断点也用不了

    maven项目编译通过,测试用例卡住,断点也用不了.如下图 maven的tomcat插件可以运行没报错,但是网页访问一直转圈 原因: 最后发现是typeAliasesPackage这里设置了别名,所以 ...

  9. ​综述 | SLAM回环检测方法

    本文作者任旭倩,公众号:计算机视觉life成员,由于格式原因,公式显示可能出问题,建议阅读原文链接:综述 | SLAM回环检测方法 在视觉SLAM问题中,位姿的估计往往是一个递推的过程,即由上一帧位姿 ...

  10. 原型工具介绍———墨刀以及Axure RP比较

    原型工具——墨刀以及Axure的比较 1759233 目录 一.了解背景... 1 二.下面分开介绍一下这两款工具... 1 2.1 Axure RP. 1 2.2墨刀... 6 三.比较... 8 ...