1. jsonCpp总所有对象、类名都在namespace json中,使用时只要包含json.h即可。
2. jsonCpp主要包含三种类型的class:value、reader、write。
(1)Json::Value root; // 建立一个 json 对象
- 新建key-value数据:
root["key1"] = Json::Value("value1"); // 新建一个 Key(名为:key1),赋予字符串值:"value1"。
root["key2"] = Json::Value(1); // 新建一个 Key(名为:key2),赋予数值:1。
root["key3"] = Json::Value(false); // 新建一个 Key(名为:key3),赋予bool值:false。
- 获取类型:
Json::ValueType type = root.type(); //可获取 root 的类型。
- 添加数组:类型数据
root["key_array"].append("string"); // 新建名为:key_array的key,对第一个元素赋值为字符串:"string"。
root["key_array"].append(22); // 为数组 key_array 赋值,对第二个元素赋值为:22。
(2)Json::Writer为纯虚类,并不能直接使用。需要使用其子类:Json::FastWriter(快,最常用)、Json::StyledWriter、Json::StyledStreamWriter。
- Json::FastWriter file; //输出json数据
cout << file.write(root) << endl;
完整的代码:
#include <json/json.h>
using namespace std;
int main()
{
Json::Value root;
root["key1"] = Json::Value("value1");
root["key2"] = Json::Value(1);
root["key3"] = Json::Value(false);
root["key_array"].append("string");
root["key_array"].append(22);
Json::FastWriter file;
cout << file.write(root) << endl;
}
输出结果为:
![]()
- Json::StyledWriter file; //输出有格式的json数据
cout << file.write(root) << endl;
完整代码:
#include <json/json.h>
using namespace std;
int main()
{
Json::Value root;
root["key1"] = Json::Value("value1");
root["key2"] = Json::Value(1);
root["key3"] = Json::Value(false);
root["key_array"].append("string");
root["key_array"].append(22);
Json::StyledWriter file;
cout << file.write(root) << endl;
}
输出结果:

(3)Json::Reader 用于读取json数据的,
代码:
#include <json/json.h>
#include <fstream>
using namespace std;
ifstream strJsonContent("jsontext.json", ios::binary); //读取jsontext.json的json文件,strJsonContent也可以为str类型
Json::Reader reader;
Json::Value root;
if (reader.parse(strJsonContent, root)) //解析strJsonContent文件
{
Json::Value::Members types = root.getMemberNames(); //得到子节点
for (Json::Value::Members::iterator it = types.begin(); it != types.end(); it++) //遍历子节点
{
Json::Value versions = root[*it];
for (unsigned int i=0; i < versions.size(); i++) {
v.push_back(versions[i].asString());
}
}
return v;
}
本文深入讲解了jsonCpp库的基本用法,包括如何创建、读取和写入JSON数据。介绍了Json::Value、Json::Reader和Json::Writer类的使用方法,以及如何通过不同子类实现快速或格式化的数据输出。
486

被折叠的 条评论
为什么被折叠?



