rapidjson的使用
C++ [ rapidjson 使用、封装、UT]、[Base64加码及解码]
Json简介
- JSON(JavaScript Object Notation)是一种轻量级、基于文本、开放的数据传输格式,适用于大多数编程语言(C++、C#、Python等)
- JSON支持多种数据类型:
enum Type {
kNullType = 0, // null 空
kFalseType = 1, // false bool类型
kTrueType = 2, // true bool类型
kObjectType = 3, // object 对象
kArrayType = 4, // array 数组
kStringType = 5, // string 字符串
kNumberType = 6 // number int、uint、float、double等
};
- JSON 仅支持两种结构:
Object(对象):键/值对(名称/值)的集合,使用花括号 { } 定义。
Array(数组):值的有序集合,使用方括号 [ ] 定义,数组中值之间用逗号分隔。
{
"Name":"rapidjson",
"ID":15,
"Struct":[ "Object", "Array"]
}
Json 构造
value的3种设置方式
#include <iostream>
#include "../rapidjson/document.h"
#include "../rapidjson/writer.h"
#include "../rapidjson/stringbuffer.h"
int main()
{
using namespace rapidjson;
Document document;
document.SetObject();
//1
Value JsonIntValue1(kNumberType); // kNumberType是命名空间rapidjson的常量
JsonIntValue1 = 100;
document.AddMember(StringRef("key"), JsonIntValue1, document.GetAllocator());
//2
Value JsonIntValue2(kNumberType);
JsonIntValue2.SetUint(100); //推荐
document.AddMember(StringRef("key1"), JsonIntValue2, document.GetAllocator());
//3
Value JsonIntValue3(100);
document.AddMember(StringRef("key2"), JsonIntValue3, document.GetAllocator());
StringBuffer strBuffer;
PrettyWriter<StringBuffer> writer(strBuffer);
document.Accept(writer);
std::string szJson = strBuffer.GetString();
std::cout << szJson << std::endl; //{"key":100,"key1":100,"key2":100}
return 0;
}
常用类型构造使用
#include <iostream>
#include "../rapidjson/document.h"
#include "../rapidjson/writer.h"
#include "../rapidjson/prettywriter.h"
#include "../rapidjson/stringbuffer.h"
int main()
{
using namespace rapidjson;
Document document;
document.SetObject();
Document::AllocatorType& Jsonallocator = document.GetAllocator();
//string type
document.AddMember(StringRef("key"), StringRef("value"), Jsonallocator);
//int type
Value JsonIntValue(kNumberType);
JsonIntValue.SetInt(100);
document.AddMember(StringRef("key"), JsonIntValue, Jsonallocator);
//uint type
Value JsonUIntValue(kNumberType);
JsonUIntValue.SetUint(100);
document.AddMember(StringRef("key1"), JsonUIntValue, Jsonallocator);
//float type
Value JsonFloatValue(kNumberType);
JsonFloatValue.SetFloat(100.23); //JsonFloatValue= 100.23; 相同
document.AddMember(StringRef("key2"), JsonFloatValue, Jsonallocator);
//double type
Value JsonDoubleValue(kNumberType);
JsonDoubleValue.SetDouble(100.2333);
document.AddMember(StringRef("key3"), JsonDoubleValue, Jsonallocator);
//bool false type
Value JsonFalseValue(kFalseType);
JsonFalseValue.SetBool(false); //JsonFalseValue= false; 相同
document.AddMember(StringRef("key4"), JsonFalseValue, Jsonallocator);
//bool true type
Value JsonTrueValue(kTrueType);
JsonTrueValue.SetBool(1);
document.AddMember(StringRef("key5"), JsonTrueValue, Jsonallocator);
StringBuffer strBuffer;
//Writer<StringBuffer> writer(strBuffer)
PrettyWriter<StringBuffer> writer(strBuffer);
document.Accept(writer);
std::string szJson = strBuffer.GetString();
std::cout << szJson << std::endl;
//判断是否存在某个key
if (document.HasMember("key1")) //true
{ std::cout << "document中存在key1." << std::endl; }
else
{ std::cout << "document中不存在key1." << std::endl; }
return 0;
}
{
"key": "value",
"key": 100,
"key1": 100,
"key2": 100.2300033569336,
"key3": 100.2333,
"key4": false,
"key5": true
}
document中存在key1.
string类型使用的两种形式
#include <iostream>
#include "../rapidjson/document.h"
#include "../rapidjson/writer.h"
#include "../rapidjson/stringbuffer.h"
int main()
{
using namespace rapidjson;
Document document;
document.SetObject();
//第一种形式
document.AddMember(StringRef("key"), StringRef("value"), document.GetAllocator());
/*//第二种形式
Value JsonKey(kStringType); //key
JsonKey.SetString("key", Jsonallocator);
Value JsonStringValue(kStringType); //string type value
JsonStringValue.SetString("StringValue", Jsonallocator);
document.AddMember(JsonKey, JsonStringValue, Jsonallocator);*/
//Json内容放到字符串中
StringBuffer strBuffer;
Writer<StringBuffer> writer(strBuffer);
document.Accept(writer);
std::string szJson = strBuffer.GetString();
std::cout << szJson << std::endl; //{"key":"value","key":"value"}
对象构造使用
#include <iostream>
#include "../rapidjson/document.h"
#include "../rapidjson/writer.h"
#include "../rapidjson/stringbuffer.h"
int main()
{
using namespace rapidjson;
Document document;
document.SetObject();
Document::AllocatorType& Jsonallocator = document.GetAllocator();
document.AddMember(StringRef("key1"), StringRef("value"), Jsonallocator);
//object type
Value JsonobjectsValue(kObjectType);
//string
JsonobjectsValue.AddMember(StringRef("class1"), StringRef("hhh"), Jsonallocator);
JsonobjectsValue.AddMember(StringRef("class1"), StringRef("ttt"), Jsonallocator);
//int
Value JsonIntValue(kNumberType);
JsonIntValue.SetInt(1001);
JsonobjectsValue.AddMember(StringRef("class2"), JsonIntValue, Jsonallocator);
//true
Value JsonTrueValue(kTrueType);
JsonTrueValue.SetBool(true);
JsonobjectsValue.AddMember(StringRef("class3"), JsonTrueValue, Jsonallocator);
document.AddMember(StringRef("key2"), JsonobjectsValue, Jsonallocator);
StringBuffer strBuffer;
PrettyWriter<StringBuffer> writer(strBuffer);
document.Accept(writer);
std::string szJson = strBuffer.GetString();
std::cout << szJson << std::endl;
return 0;
}
{
"key1": "value",
"key2": {
"class1": "hhh",
"class1": "ttt",
"class2": 1001,
"class3": true
}
}
Array构造使用
#include <iostream>
#include "../rapidjson/document.h"
#include "../rapidjson/writer.h"
#include "../rapidjson/prettywriter.h"
#include "../rapidjson/stringbuffer.h"
int main()
{
using namespace rapidjson;
Document document;
document.SetObject();
Document::AllocatorType& Jsonallocator = document.GetAllocator();
document.AddMember(StringRef("key1"), StringRef("value"), Jsonallocator);
Value JsonArrayValue(kArrayType);
//string
Value JsonStringValue(kStringType);
JsonStringValue.SetString("test");// "test"
JsonArrayValue.PushBack(JsonStringValue, Jsonallocator);
//int
Value JsonIntValue(kNumberType);
JsonIntValue.SetInt(1001);//1001
JsonArrayValue.PushBack(JsonIntValue, Jsonallocator);
//object type
Value JsonobjectsValue(kObjectType);
JsonobjectsValue.AddMember(StringRef("class1"), StringRef("ttt1"), Jsonallocator);//"class1": "ttt1"
JsonobjectsValue.AddMember(StringRef("class1"), StringRef("ttt1"), Jsonallocator);//"class1": "ttt1"
JsonobjectsValue.AddMember(StringRef("class2"), StringRef("ttt2"), Jsonallocator);//"class2": "ttt2"
JsonArrayValue.PushBack(JsonobjectsValue, Jsonallocator);
document.AddMember(StringRef("key2"), JsonArrayValue, Jsonallocator);
//{"key1":"value","key2":["test",1001,{"class1":"ttt1","class1":"ttt1","class2":"ttt2"}]}
StringBuffer strBuffer;
PrettyWriter<StringBuffer> writer(strBuffer);
document.Accept(writer);
std::string szJson = strBuffer.GetString();
std::cout << szJson << std::endl;
return 0;
}
{
"key1": "value",
"key2": [
"test",
1001,
{
"class1": "ttt1",
"class1": "ttt1",
"class2": "ttt2"
}
]
}
Json 解析
常用类型解析
//IsString() //是否是string
//IsInt() //是否是int
//IsArray() //是否是array
//IsDouble() //是否是double
//IsFloat() //是否是float
//IsBool() //是否是bool类型
//IsTrue() //是否是true
//IsObject() //是否是object
#include <iostream>
#include "../rapidjson/document.h"
std::string szJson = "{\"project\":\"rapidjson\",\"stars\":10}";
int main()
{
using namespace rapidjson;
Document document;
if (document.Parse(szJson.c_str()).HasParseError()) //解析Json
{
std::cout << "Json parse error." << std::endl;
return 0;
}
if (!document.IsObject()) //判断是否是对象
{
std::cout << "szJson is not object." << std::endl;
return 0;
}
//获取key的value可以用迭代器查找,也可以直接获取,类似map中找key
auto iter = document.FindMember("project"); //迭代器查找key
if (document.MemberEnd() != iter)
{
if (iter->value.IsString()) //Value的类型是否是string
{
std::string szValue = iter->value.GetString();
std::cout << "szValue: "<< szValue << std::endl; //szValue: rapidjson
}
}
const Value& ValueInt = document["stars"]; //直接获取key的value,若key不存在,获取内容为空
if (ValueInt.IsInt())
{
std::cout << "Int value: " << ValueInt.GetInt() << std::endl; //Int value: 10
}
return 0;
}
object类型解析
#include <iostream>
#include "../rapidjson/document.h"
#include "../rapidjson/stringBuffer.h"
#include "../rapidjson/writer.h"
using namespace rapidjson;
std::string JsonToString(rapidjson::Value& valValue)
{
StringBuffer strBuffer;
Writer<StringBuffer> writer(strBuffer);
valValue.Accept(writer);
return strBuffer.GetString();
}
std::string szJson = "{\"key\":{\"project\":\"rapidjson\",\"stars\":10}}";
int main()
{
std::cout << "szJson: "<< szJson << std::endl; //szJson: {"key":{"project":"rapidjson","stars":10}}
Document document;
if (document.Parse(szJson.c_str()).HasParseError()) //解析Json
{
std::cout << "Json parse error." << std::endl;
return 0;
}
if (!document.IsObject()) //判断是否是object
{
std::cout << "szJson is not object." << std::endl;
return 0;
}
auto iter = document.FindMember("key");
if (document.MemberEnd() == iter)
{
std::cout << "Find not key." << std::endl;
return 0;
}
if (!iter->value.IsObject()) //Value的类型是否是object
{
std::cout << "Key is not object." << std::endl;
return 0;
}
Value objValue = iter->value.GetObject();
std::cout << "szJsonObj: " << JsonToString(objValue)<< std::endl; //szJsonObj: {"project":"rapidjson","stars":10}
return 0;
}
array解析
#include <iostream>
#include "../rapidjson/document.h"
std::string szJson = "{ \"Key\": [\"value1\",\"value2\",\"value3\"] }";
int main()
{
std::cout << "szJson: "<< szJson << std::endl; //szJson: { "Key": ["value1","value2","value3"] }
using namespace rapidjson;
Document document;
if (document.Parse(szJson.c_str()).HasParseError()) //解析Json
{
std::cout << "Json parse error." << std::endl;
return 0;
}
auto& valArray = document["Key"];
if (valArray.IsArray())
{
int iSize = valArray.Size();
std::cout << "Array size: "<< iSize << std::endl; //Array size: 3
for (int i = 0; i < iSize; ++i)
{
Value& valTmp = valArray[i];
if (valTmp.IsString())
{
std::string tszTemp = valTmp.GetString();
std::cout << "Array value: " << tszTemp << std::endl; //Array value: value1 //Array value: value2 //Array value: value3
}
else
std::cout << "Array value is not string." << std::endl;
}
}
return 0;
}
参考文献
JSON教程
Rapidjson的简单使用
Tencent/rapidjson使用说明及下载
Tencent/rapidjson库下载
JSON对比工具
c++json库(jsoncpp)简单使用(包含下载使用方法,中文错误解决方案)