源码地址: 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(); }