Jsoncpp下载地址:
编译生成后的库文件为:jsoncpp.lib
下面是一个使用的demo,copy过去自己看看就会了:
#include <iostream>
#include <fstream>
#include <ostream>
#include <assert.h>
#include <string>
#include "json\json.h" //Jsoncpp的头文件
#pragma comment(lib, "jsoncpp.lib")
int main()
{
Json::Value jsonRoot; //定义根节点
Json::Value jsonItem; //定义一个子对象
Json::CharReaderBuilder builder;
Json::CharReader* reader(builder.newCharReader());
/*******************从Json字符串读取***********************/
JSONCPP_STRING errs;
const char* str = "{\n\t\"people1\" : \n\t{\n\t\t\"age\" : 20,\n\t\t\"name\" : \"ZhangSan\"\n\t},\n\t\"people2\" : \n\t{\n\t\t\"age\" : 19,\n\t\t\"name\" : \"LiSi\"\n\t}\n}\n";
bool ok = reader->parse(str, str + std::strlen(str), &jsonRoot, &errs);
std::string name = jsonRoot["people1"]["name"].asString(); //"ZhangSan"
int age = jsonRoot["people2"]["age"].asInt(); //19
size_t len = jsonRoot.size();// 2 //Json数组的长度
jsonRoot.clear();//清除jsonRoot
/*********************生成Json字符串*********************/
jsonItem["name"] = "ZhangSan"; //添加数据1
jsonItem["age"] = 20;
//jsonRoot.append(jsonItem); //添加匿名对象
jsonRoot["people1"] = jsonItem;
jsonItem.clear(); //清除jsonItem
jsonItem["name"] = "LiSi"; //添加数据2
jsonItem["age"] = 19;
jsonRoot["people2"] = jsonItem;
name = jsonRoot["people1"]["name"].asString(); //"ZhangSan"
age = jsonRoot["people2"]["age"].asInt(); //19
/***********************保存为字符串*********************/
std::string outStr = jsonRoot.toStyledString(); //保存为字符串
std::cout << outStr << std::endl; //输出字符串到控制台
/**********************遍历Json数组对象******************/
for (auto v : jsonRoot)
{
name = v["name"].asString();
age = v["age"].asInt();
}
/***********************输出到文件*********************/
std::ofstream ofs; //标准输出流
ofs.open("sample.json"); //创建文件
ofs << jsonRoot.toStyledString(); //输出
ofs.close();
/***********************从文件读取*********************/
std::ifstream ifs; //标准输入流
ifs.open("sample.json");
assert(ifs.is_open());
jsonRoot.clear();
builder["collectComments"] = false;
bool success = parseFromStream(builder, ifs, &jsonRoot, &errs); //从ifs中读取数据到jsonRoot
len = jsonRoot.size();
name = jsonRoot["people2"]["name"].asString(); //"Lisi"
age = jsonRoot["people1"]["age"].asInt(); //20
ifs.close();
system("pause");
return 0;
}