由于项目需求,需要将数据存储为json格式,于是花了点时间编译json的源码;网上的编译json之后,调用API的方法会出如下错误 :“error C4996: 'Json::Reader': Use CharReader and CharReaderBuilder instead”;接下来本人会贴出编译和调用jsoncpp的方法。
一、编译json
先在github上下载源码,链接:https://github.com/open-source-parsers/jsoncpp,打开makefiles\msvc2010\jsoncpp.sln,编译成功后生成lib_json.lib文件
二、配置json
将jsoncpp-master/include/json配置到编译器的包含目录,再将lib_json.lib所在目录配置到库目录
三、在vs2015中使用json
#include <string>
#include <iostream>
#include <json.h>
#include <fstream>
#include <memory>
#pragma comment(lib, "lib_json")
void testjson(std::map<std::string, std::string> mydata)
{
Json::Value root;
Json::StreamWriterBuilder builder;
builder["commentStyle"] = "None";
builder["indentation"] = "";
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
Json::Value data;
std::map<std::string, std::string>::iterator iter;
for (iter = mydata.begin(); iter != mydata.end(); iter++)
{
data[iter->first] = iter->second;
}
root.append(data);
std::ofstream ofs;
ofs.open("result.json", std::ios::app);
writer->write(root, &ofs);
}
void main(int argc, char** argv)
{
std::map<std::string, std::string> mapMainInfo;
mapMainInfo.insert(std::pair<std::string, std::string>("country", "chinese"));
testjson(mapMainInfo);
system("pause");
}