JsonCpp是一个开源库
下载地址:https://github.com/open-source-parsers/jsoncpp
文档地址:http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html
使用
官方提供的集成方案:
https://github.com/open-sourceparsers/jsoncpp/wiki/Amalgamated
下载jsoncpp之后,打开makefiles文件夹,里面msvc2010和vs71。使用vs2015编译msvc2010里面的jsoncpp.sln文件,不要使用vs71里面的。不然后面会出现问题,且按照网上给出的解决办法也无法解决。
编译jsoncpp.sln,生成debug->lib_json.lib release->lib_json.lib.
- 将生成的.lib和整个include\json文件夹拷贝到自己的项目中,在调用时,配置相关属性。属性配置时,注意C/C++——>代码生成——>运行库的选择“多线程调试(/MTd)”和“多线程(/MT)”,和jsoncpp.sln的配置保持一致。
- 使用jsoncpp库时,需要包含头文件
#include<json/json.h>
,命名空间Json。
下面给出解析字符串和文件的例子:
int ParseJsonFromString()
{
const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";
Json::CharReaderBuilder builder;
Json::CharReader* reader(builder.newCharReader());
Json::Value root;
JSONCPP_STRING errs;
bool ok = reader->parse(str, str + strlen(str), &root, &errs);
if (ok&&errs.size() == 0) // reader将Json字符串解析到root,root将包含Json里所有子元素
{
std::string upload_id = root["uploadid"].asString(); // 访问节点,upload_id = "UP000000"
int code = root["code"].asInt(); // 访问节点,code = 100
}
return 0;
}
int ParseJsonFromFile(const char* filename)
{
// 解析json用Json::Reader 以前的接口,现在换了
Json::Value root;
Json::CharReaderBuilder builder;
builder["collectComments"] = false;
string errs;
std::ifstream ifs;
ifs.open(filename);
assert(ifs.is_open());
bool ok = Json::parseFromStream(builder, ifs, &root, &errs);
if (!ok)
{
cout << errs << endl;
}
return 0;
}
参考:
https://www.cnblogs.com/esCharacter/p/7657676.html
https://stackoverflow.com/questions/47257198/parsing-issue-warning-with-json
http://www.cplusplus.com/forum/general/184255/