1、最新的下载地址 https://github.com/open-source-parsers/jsoncpp
此版本最好用vs2010以上版本编译 。
用vs2008由于缺失stdint.h导致编译失败,网上大神自定义头文件的方式
#ifdef _MSC_VER
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
Visual Studio 2003 - 2008 (Visual C++ 7.1 - 9) don't claim to be C99 compatible
不过试了,不好用。
所以直接用vs2010以上编译了,此版本以上自带 stdint.h 头文件
2、解压之后 打开 jsoncpp-master\makefiles\msvc2010\jsoncpp.sln 编译即可。
3、使用demo
//工程属性 ->c/c++ ->代码生成->运行库->记得要和生成的lib_json.lib选项一致,
//我这里是多线程调试 (/MTd) 否则编译不过的!!
#include "stdafx.h"
#include "json\json.h"
#include<string>
#include<iostream>
#include <memory>
#include<fstream>
using namespace std;
#pragma comment(lib, "lib_json.lib")
int main()
{
Json::Value val;
Json::StreamWriterBuilder style_write;
val["name"] = "xiaoli";
val["age"] = 10;
val["class"] = "class2";
//设置默认格式
style_write["commentStyle"] = "None";
style_write["indentation"] = "";
std::unique_ptr<Json::StreamWriter> writer(style_write.newStreamWriter());
std::ofstream ofs;
ofs.open("result.json", std::ios::app);
writer->write(val, &ofs);
ofs.close();
Json::Reader read;
//从文件中读取,保证当前文件有test.json文件
std::ifstream in("result.json", ios::binary);
if (!in.is_open())
{
cout << "Error opening file\n";
return -1;
}
Json::Value root;
if (read.parse(in, root))
{
std::string name = root["name"].asString();
int nAge = root["age"].asInt();
std::string class_name = root["class"].asString();
cout << "name: " << name.c_str() << " age: " << nAge << " class: " << class_name.c_str() << endl;
}
in.close();
return 0;
}