rapidjson嵌套对象中修改/增加键值

2020-07-01  本文已影响0人  小怪兽狂殴奥特曼
#include <iostream>

#include "rapidjson/document.h"        // rapidjson's DOM-style API
#include "rapidjson/prettywriter.h"    // for stringify JSON
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"

int main() {
    std::string info="{\"hello\":\"world!\",\"param\":{\"id\":100}}";
    rapidjson::Document root;
    root.Parse(info.c_str());

    std::string val="bac";
    rapidjson::Value k;
    k.SetString(val.c_str(), val.size());

    rapidjson::Value params;
    params=root["param"];

    // 先读取嵌套对象param
    std::string result1;
    {
        rapidjson::StringBuffer buffer1;
        rapidjson::Writer<rapidjson::StringBuffer> writer1(buffer1);
        params.Accept(writer1);
        result1 = buffer1.GetString();
        //std::cout<<result1<<std::endl;
    }

    // 在param对象中增加字段(修改同理)
    rapidjson::Document docParam;
    docParam.Parse(result1.c_str());
    docParam.AddMember("age", 15, docParam.GetAllocator());
    {
        rapidjson::StringBuffer buffer1;
        rapidjson::Writer<rapidjson::StringBuffer> writer1(buffer1);
        docParam.Accept(writer1);
        result1 = buffer1.GetString();
        //std::cout<<result1<<std::endl;
    }

    root.AddMember("param", docParam, root.GetAllocator());
    root.RemoveMember("param");
    {
        rapidjson::StringBuffer buffer1;
        rapidjson::Writer<rapidjson::StringBuffer> writer1(buffer1);
        root.Accept(writer1);
        result1 = buffer1.GetString();
        std::cout<<result1<<std::endl;
    }

    return 0;
}

垃圾的rapidjson库,文档垃圾,接口设计反人类,号称高性能,改个键值要写这么多行代码,又长又臭,增加了维护难度,搞不好性能更低了。
垃圾。。

上一篇下一篇

猜你喜欢

热点阅读