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)简单使用(包含下载使用方法,中文错误解决方案)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qzy0621

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值