JsonCpp是一个基于C++语言的开源库,用于C++程序的Json数据的读写操作,本文重点给大家介绍C++qt使用jsoncppjson读写操作,感兴趣的朋友跟随小编一起看看吧
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工程下载地址:点击此处下载
到此这篇关于C++ qt 使用jsoncpp json 读写的文章就介绍到这了,更多相关C++ qt 使用jsoncpp json内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:C++ qt 使用jsoncpp json 读写操作
基础教程推荐
- C/C++编程中const的使用详解 2023-03-26
- C++中的atoi 函数简介 2023-01-05
- 一文带你了解C++中的字符替换方法 2023-07-20
- 详解c# Emit技术 2023-03-25
- 如何C++使用模板特化功能 2023-03-05
- C语言基础全局变量与局部变量教程详解 2022-12-31
- C利用语言实现数据结构之队列 2022-11-22
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C语言 structural body结构体详解用法 2022-12-06
- C++详细实现完整图书管理功能 2023-04-04