jsonCPP

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);
	}
}
posted @   半夜打老虎  阅读(465)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示