rapidJson使用

1.官方文档

http://rapidjson.org/zh-cn/md_doc_tutorial_8zh-cn.html#CreateString

2.添加元素

#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "rapidjson/document.h"

void rapid_json_test() {
    rapidjson::Document document;
    rapidjson::Document::AllocatorType& alloc = document.GetAllocator();

    rapidjson::Value json_normal(rapidjson::Type::kObjectType);

    // Object中加key:"value",3中不同key,value的添加形式
    json_normal.AddMember("key_name", "111", alloc);
    std::string str_tmp("value1_" + std::to_string(1));
    json_normal.AddMember("key2_2",
                          rapidjson::Value().SetString(str_tmp.c_str(), str_tmp.length(), alloc).Move(), alloc);
    std::string str_key3("key3_" + std::to_string(3));
    std::string str_val3("value3_" + std::to_string(3));
    json_normal.AddMember(rapidjson::Value(str_key3.c_str(), str_key3.length(), alloc).Move(),
                          rapidjson::Value(str_val3.c_str(), str_val3.length(), alloc).Move(),
                          alloc);

    // Array
    rapidjson::Value json_array(rapidjson::Type::kArrayType);
    // Araay中添加元素
    json_array.PushBack(json_normal.Move(), alloc);  // Object
    std::string err_str("error,key:" + std::string("keyx"));
    json_array.PushBack(rapidjson::Value(err_str.c_str(), err_str.length(), alloc), alloc);  // String

    // 转String
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    json_array.Accept(writer);

    std::cout << "final string:\n" << buffer.GetString() << "\n";
}

效果:

[{"key_name":"111","key2_2":"value1_1","key3_3":"value3_3"},"error,key:keyx"]

3.解析Json

const char* response_data = "{\"key\":123}";
rapidjson::Document document;
document.Parse<0>(response_data);

if (document.HasMember("key") && ducument["key"].IsInt()) {
    int value = ducument["key"].GetInt();
}

注:

1.Array类型的Json中是不允许出现 key:"value"的形式的,如果强行AddMember, 那么只会显示key

2.Object中要求每一项必须有key

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值