Json---使用Jsoncpp解析与写入

时间:2023-03-10 06:25:59
Json---使用Jsoncpp解析与写入

上述Json解析使用的是Jsoncpp,要使用Jsoncpp,得做如下几步的配置:

  1.首先从http://sourceforge.net/projects/jsoncpp/下载,压缩包大约105k。

  2.解压之后,将include文件夹、src下的lib_json文件夹,拷贝至你的项目中。

Json---使用Jsoncpp解析与写入

  3.项目属性->C/C++->常规->附加包含目录  添加3个路径:①..\include、 ②..\include\json、 ③..\lib_json。

  4.项目中添加lib_json下的3个cpp文件:①json_reader.cpp  ②json_value.cpp  ③json_writer.cpp。并右键这三cpp文件,属性->C/C++->预编译头->创建/使用预编译头->不使用预编译头。否则编译报错。

  5.项目cpp中#include "json.h"。

  这样就可以愉快的使用Jsoncpp解析Json了。

  JsonDemo.cpp:

#include <fstream>
#include "json.h"
using namespace std;

int JsonRead()
{
ifstream ifs;
ifs.open("testR.json");

Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs,root,false))
{
return -1;
}

string name = root["name"].asString();
int age = root["age"].asInt();

cout<<name<<endl;
cout<<age<<endl;
getchar();
return 0;
}

int JsonWrite()
{
Json::Value root;
Json::FastWriter writer;
Json::Value person;

person["name"] = "往事随风";
person["age"] = 23;
root.append(person);

string json_file = writer.write(root);

ofstream ofs;
ofs.open("testW.json");
ofs<<json_file;
getchar();
return 0;
}

int main()
{
JsonRead();
JsonWrite();
return 0;
}