jsoncpp
是一个用于操作json
数据的C++开源库
代码地址:https://github.com/open-source-parsers/jsoncpp
使用文档:http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html
使用过程中遇到一个错误,这里作为记录
错误
error C4996: 'Json::Reader': Use CharReader and CharReaderBuilder instead
error C4996: 'Json::Reader::Reader': Use CharReader and CharReaderBuilder instead
解决方法
Json::CharReaderBuilder readerBuild;
Json::CharReader* reader(readerBuild.newCharReader());
示例
#include <iostream>
#include "json/json.h"
int main()
{
std::cout << "Hello world" << std::endl;
const char* strValue = "{"file_path": "./test_models/test.obj", "filename":"test.obj", "code_id": 3 }";
Json::CharReaderBuilder readerBuild;
Json::CharReader* jsonReader(readerBuild.newCharReader());
Json::Value jsonValue;
JSONCPP_STRING jsonErrs;
bool isParse = jsonReader->parse(strValue, strValue + std::strlen(strValue), &jsonValue, &jsonErrs);
if (isParse && 0 == jsonErrs.size()){
std::string filePath = jsonValue["file_path"].asString();
std::string fileName = jsonValue["filename"].asString();
int codeId = jsonValue["code_id"].asInt();
std::cout << "filePath: " << filePath << " fileName: " << fileName << " codeId: " << codeId << std::endl;
}
return 0;
}
解析服务端返回的json数据
void stringReplace(std::string& strOri, const std::string& strsrc, const std::string& strdst) {
std::string::size_type pos = 0;
std::string::size_type srclen = strsrc.size();
std::string::size_type dstlen = strdst.size();
while ((pos = strOri.find(strsrc, pos)) != std::string::npos) {
strOri.replace(pos, srclen, strdst);
pos += dstlen;
}
}
bool parseResult(std::string & predictRes, std::vector<int> & labels){
// parse result
stringReplace(predictRes, "\"", """);
predictRes = std::string(predictRes, 1, predictRes.size() - 2);
Json::CharReaderBuilder readerBuild;
Json::CharReader* reader(readerBuild.newCharReader());
Json::Value rcvRes;
JSONCPP_STRING jsonErrs;
bool parseOK = reader->parse(predictRes.c_str(), predictRes.c_str() + predictRes.size(), &rcvRes, &jsonErrs);
delete reader;
if (!parseOK) {
//std::cout << "Failed to parse the rcvRes!" << std::endl;
return false;
}
std::string returnCode = rcvRes["returnCode"].asString(); // "Successed!" or "Failed!"
if (returnCode != "Successed!") {
//std::cout << "Predict is Failed" << std::endl;
return false;
}
// get labels
labels.clear();
Json::Value rcvResItem;
int rcvSize = rcvRes["text"][0].size();
for (int i = 0; i < rcvSize; ++i) {
rcvResItem = rcvRes["text"][0][i];
int label = rcvResItem.asInt();
labels.push_back(label);
}
}