JsonCpp的使用
项目需要c++下使用json,我选择了JsonCpp,官网是:https://github.com/open-source-parsers/jsoncpp。
解压后使用python编译出两个h文件和一个cpp文件:
(电脑需要安装python自己百度安装,这里就不说了)
安装python后,打开windows下cmd窗口,进入到jsoncpp文件夹 如图:

执行命令:python amalgamate.py 就会生成dist文件夹 里面有 json.h json-forwards.h jsoncpp.cpp三个文件:如下

将三个文件加入到工程即可使用,我是要qt进行测试使用:

main.cpp如下
#include <iostream>
#include <fstream>
#include "dist/json/json.h"
using namespace std;
int main(int argc, char *argv[])
{
// write
Json::Value people1;
people1["name"] = "Dione";
people1["sex"] = "男";
people1["age"] = 24;
people1["note"] = "jsoncpp write test!";
Json::Value people2;
people2["name"] = "Hulis";
people2["sex"] = "女";
people2["age"] = 22;
people2["note"] = "jsoncpp write test!";
Json::Value peoples;
peoples.append(people1);
peoples.append(people2);
Json::Value writeValue;
writeValue["classname"] = "三年一班";
writeValue["peoples"] = peoples;
Json::FastWriter fwriter;
std::string strf = fwriter.write(writeValue);
std::ofstream ofsf("example_fast_writer.json");
ofsf << strf;
ofsf.close();
Json::StyledWriter swriter;
std::string strs = swriter.write(writeValue);
std::ofstream ofss("example_styled_writer.json");
ofss << strs;
ofss.close();
// read
string strValue = "{\"key1\":\"111\",\"array\":[{\"key2\":\"222\"},{\"key2\":\"333\"},{\"key2\":\"444\"}]}";
Json::Reader reader;
Json::Value root;
if (reader.parse(strValue, root))
{
std::string out = root["key1"].asString();
qDebug()<<QString::fromStdString(out);
Json::Value arrayObj = root["array"];
for (int i=0; i<arrayObj.size(); i++)
{
out = arrayObj[i]["key2"].asString();
qDebug()<<QString::fromStdString(out);
}
}
std::ifstream ifs("example_fast_writer.json");
if (reader.parse(ifs, root))
{
std::string out = root["classname"].asString();
qDebug()<<QString::fromStdString(out);
Json::Value peoples = root["peoples"];
for (int i=0; i<peoples.size(); i++)
{
qDebug()<<QString::fromStdString(peoples[i]["name"].asString());
qDebug()<<QString::fromStdString(peoples[i]["sex"].asString());
qDebug()<<QString::fromStdString(peoples[i]["age"].asString());
qDebug()<<QString::fromStdString(peoples[i]["note"].asString());
}
}
return 0;
}
会生成两个json文件,一个是没有格式写入一个是有格式写入,如下:

Demo工程下载地址:点击此处下载
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)