json::rapidjson工具

醉酒当歌 提交于 2019-11-27 21:13:17

 

源码地址: https://github.com/Tencent/rapidjson 可跨平台使用。将 rapidjson-master\include\rapidjson 中的 rapidjson 文件夹添加到 项目中 即可。

 

#pragma once
#include <type_traits>
#include <rapidjson/error/en.h>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/reader.h>
#include <rapidjson/error/en.h>

template<typename T>
bool safe_get_json_member(rapidjson::Value& v, const char* field, T& r)
{
    if (!v.HasMember(field))
        return false;

    return safe_get_json_val(v[field], r);
}

 

std::string Json2str()
{
    std::lock_guard<mutex> lck(m_mx);
    Document doc;
    doc.SetObject();

    Document::AllocatorType& allocator = doc.GetAllocator();

    Value base(rapidjson::kObjectType);
    
    base.AddMember("SnapPicturePath", StringRef(m_bc.SnapPicturePath.c_str()), allocator);
    base.AddMember("vehThreadNum", StringRef(m_bc.vehThreadNum.c_str()), allocator);
    base.AddMember("vehUrl", StringRef(m_bc.vehUrl.c_str()), allocator);
    base.AddMember("cmsUrl", StringRef(m_bc.cmsUrl.c_str()), allocator);
    
    doc.AddMember("base", base, allocator);
    rapidjson::StringBuffer buffer;
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
    doc.Accept(writer);

    return buffer.GetString();
}

 


std::string str2json(string str)
{    Document doc;
    doc.Parse<0>(str.c_str());
    if (doc.HasParseError()) {
        return false;
    }

    Value* pValue = nullptr;
    Value* Value = nullptr;
    safe_get_json_member(doc, "result", pValue);

    if(safe_get_json_member(*pValue, "image", Value))
      outHexImage = Value->GetString();
    if(safe_get_json_member(*pValue, "confidence", Value))
      confidence = Value->GetString(); }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!