JsonCpp的核心类及核心函数使用汇总
文章目录
- JsonCpp的核心类及核心函数使用汇总
- 一、前言
- 二、JsonCpp 核心类介绍
- 三、`Value` 类函数解析
- 1. 值获取函数(`asxxx` 系列 )
- 2. 值类型判断函数(`isxxx` 系列 )
- 3. 数组操作函数
- 4. 对象操作函数
- 5. 运算符重载
- 6. 迭代器
- 7. JSON 转化
- 四、Json::Reader 和 Json::Writer 类
- 1. Json::Reader 类:反序列化 - 解析函数
- (一)核心作用
- (二)`parse` 函数重载说明
- (三)使用示例
- 3.Json::Writer 类:序列化 - 写入
- (一)核心作用
- (二)常用子类及特点
- 1. `Json::StyledWriter`
- 2. `Json::FastWriter`
- (三)使用示例(结合读写 )
JsonCpp的核心类及核心函数使用汇总
一、前言
在 C++ 开发中,处理 JSON 数据是常见需求,JsonCpp 是个实用的 C++ JSON 解析库。本文总结 JsonCpp 中常见的核心类和函数的使用,帮助掌握 JSON 数据处理。
二、JsonCpp 核心类介绍
类 | 说明 |
---|---|
Json::Value | 类型支持类,可解析所有 JSON 支持类型(bool、字符串、浮点数、对象、数组等 );支持用 isxxx 判断类型、asxxx 转换类型,能按 JSON 字段格式提取值(如 asString 取字符串节点值 ) |
Json::Reader | 可解析文件、文件流、字符串内存,结果存入 Json::Value ;支持用 Features 定义 JSON 严格等级,影响解析失败时函数返回逻辑 |
Json::Writer | 基类,用于将数据转为字符串流(内存 )并可写入文件;需用实现子类(如 Json::FastWriter 压缩 JSON 后写入,Json::StyledWriter 按自定义格式输出 ) |
三、Value
类函数解析
1. 值获取函数(asxxx
系列 )
asxxx
函数用于类型转换,前提是 Value
存储对应类型数据,否则可能出问题,建议先用 isxxx
判断。示例:
#include <json/json.h>
#include <iostream>
using namespace std;int main() {Json::Value val;val = "Hello JsonCpp";if (val.isString()) {string str = val.asString(); cout << "字符串值:" << str << endl;}val = 123;if (val.isInt()) {int num = val.asInt(); cout << "整数值:" << num << endl;}return 0;
}
常用 asxxx
函数:
函数 | 功能 |
---|---|
const char* asCString() const | 获取 C 风格字符串 |
string asString() const | 转成 std::string |
Int asInt() const | 转 int 类型(Int 一般是 int 别名 ) |
UInt asUInt() const | 转 unsigned int 类型 |
double asDouble() const | 转 double 类型 |
bool asBool() const | 转 bool 类型 |
2. 值类型判断函数(isxxx
系列 )
- 用于判断
Value
存储数据类型,精准操作 JSON 数据关键。函数及功能:
函数 | 功能 |
---|---|
bool isNull() const | 是否为 null 类型 |
bool isBool() const | 是否为 bool 类型 |
bool isInt() const | 是否为 int 类型 |
bool isInt64() const | 是否为 int64_t 类型 |
bool isUInt() const | 是否为 unsigned int 类型 |
bool isUInt64() const | 是否为 uint64_t 类型 |
bool isIntegral() const | 是否为整数类型(int 、uint 等整数相关类型 ) |
bool isDouble() const | 是否为 double 类型 |
bool isNumeric() const | 是否为数值类型(整数、浮点数 ) |
bool isString() const | 是否为字符串类型 |
bool isArray() const | 是否为数组类型(JSON 数组 [] ) |
bool isObject() const | 是否为对象类型(JSON 对象 {} ) |
- 示例:
Json::Value val;
val = Json::arrayValue;
if (val.isArray()) {cout << "是数组类型" << endl;
}
val = Json::objectValue;
if (val.isObject()) {cout << "是对象类型" << endl;
}
3. 数组操作函数
Json::Value
数组操作通过一系列函数实现,ArrayIndex
是unsigned int
类型,代表数组索引。
函数 | 功能 |
---|---|
Value get(ArrayIndex index, const Value& defaultValue) const | 按索引 index 取数组元素,无则返回 defaultValue |
bool isvalidIndex(ArrayIndex index) const | 判断索引 index 是否有效 |
Value& append(Value& value) | 添加元素到数组末尾 |
bool insert(ArrayIndex index, const Value& newValue) | 在索引 index 处插入元素 |
bool removeIndex(ArrayIndex index, Value* removed) | 删除索引 index 元素,removed 存删除元素 |
bool empty() const | 判断数组是否为空(对象为空或 null 也返回 true ) |
void clear() | 清空数组元素(对象则删除所有成员 ) |
void resid(ArrayIndex newSize) | 调整数组大小到 newSize |
- 示例:
Json::Value arr(Json::arrayValue);
arr.append("元素1");
arr.append(123);
// 遍历数组
for (Json::ArrayIndex i = 0; i < arr.size(); ++i) {cout << "数组元素:" << arr[i] << endl;
}
// 插入元素
arr.insert(1, "插入元素");
// 删除元素
Json::Value removed;
arr.removeIndex(2, &removed);
cout << "删除元素:" << removed << endl;
4. 对象操作函数
- 处理 JSON 对象(键值对形式 ),
Members
一般是vector<string>
类型,存对象成员名。
函数 | 功能 |
---|---|
Members getMemberNames() const | 获取对象所有键名,返回 vector<string> |
bool isMember(const char* key) const | 判断是否有 key 对应的成员 |
void removeMember(const char* key) | 删除 key 对应的成员 |
Value get(const char* key, const Value& defaultValue) const | 按 key 取成员值,无则返回 defaultValue |
示例:
Json::Value obj(Json::objectValue);
obj["name"] = "JsonCpp";
obj["version"] = 1.0;
// 获取成员名
Json::Value::Members members = obj.getMemberNames();
for (const auto& member : members) {cout << "成员名:" << member << ",值:" << obj[member] << endl;
}
// 判断成员
if (obj.isMember("name")) {cout << "存在 name 成员" << endl;
}
// 删除成员
obj.removeMember("version");
5. 运算符重载
Json::Value
重载 []
运算符,方便像数组或对象一样访问元素:
- 数组访问:
Value& operator[](ArrayIndex index);
,按索引操作数组元素。 - 对象访问:
Value& operator[](const char* key);
,按键操作对象成员。
示例:
Json::Value root;
root["array"][0] = "数组元素";
root["object"]["key"] = "对象值";
cout << "数组元素:" << root["array"][0] << endl;
cout << "对象值:" << root["object"]["key"] << endl;
6. 迭代器
遍历 Json::Value
(数组或对象 ),分常量迭代器(只读 )和普通迭代器(可修改 )。
函数 | 功能 |
---|---|
const_iterator begin() const | 常量迭代器起始,只读 |
const_iterator end() const | 常量迭代器结束 |
iterator begin() | 普通迭代器起始,可修改 |
iterator end() | 普通迭代器结束 |
示例:
Json::Value arr(Json::arrayValue);
arr.append("元素1");
arr.append("元素2");
// 常量迭代器遍历(只读)
for (Json::Value::const_iterator it = arr.begin(); it != arr.end(); ++it) {cout << "常量遍历:" << *it << endl;
}
// 普通迭代器遍历(可修改)
for (Json::Value::iterator it = arr.begin(); it != arr.end(); ++it) {*it = "修改后_" + it->asString(); cout << "修改遍历:" << *it << endl;
}
7. JSON 转化
Json::Value
可转成字符串,string Value::toStyledString() const
生成带缩进格式化字符串,方便查看;若要无格式化或自定义输出,用 Json::Writer
子类(如 FastWriter
紧凑格式)。示例:
Json::Value val;
val["name"] = "Test";
val["age"] = 20;
string styledStr = val.toStyledString();
cout << "格式化字符串:\n" << styledStr << endl;Json::FastWriter fastWriter;
string fastStr = fastWriter.write(val);
cout << "快速输出字符串:" << fastStr << endl;
四、Json::Reader 和 Json::Writer 类
在 JsonCpp 库里,Json::Reader
负责把 JSON 格式的文本数据解析成 Json::Value
对象(反序列化),Json::Writer
及其子类则用于把 Json::Value
对象转换成 JSON 格式的字符串(序列化 )。
1. Json::Reader 类:反序列化 - 解析函数
(一)核心作用
把 JSON 格式的字符串、文件流等数据,解析成 Json::Value
类型的对象,让程序能像操作普通数据结构(对象、数组等 )一样处理 JSON 内容。
(二)parse
函数重载说明
Json::Reader
提供了 3 个常用的 parse
重载函数,适配不同输入场景:
// 1. 解析 std::string 类型的 JSON 文本
bool parse(const std::string& document, Value& root, bool collectComments = true); // 2. 解析字符数组形式的 JSON 文本(beginDoc 起始、endDoc 结束 )
bool parse(const char* beginDoc, const char* endDoc, Value& root, bool collectComments = true); // 3. 解析输入流(如文件流 std::ifstream )里的 JSON 内容
bool parse(Istream& is, Value& root, bool collectComments = true);
- 参数说明:
document
/beginDoc
+endDoc
/is
:待解析的 JSON 数据源,分别对应字符串、字符数组范围、输入流。root
:解析结果会存储到这个Json::Value
对象里,后续通过它访问 JSON 数据。collectComments
:是否收集 JSON 里的注释,默认true
。一般场景不用刻意关注,保持默认即可;若要严格忽略注释提升解析效率,可设为false
。
- 返回值:
bool
类型,true
表示解析成功,false
表示解析失败(如 JSON 格式错误 )。
(三)使用示例
假设我们有一段 JSON 格式的字符串,想解析它:
#include <json/json.h>
#include <iostream>
#include <string>
using namespace std;int main() {// 模拟从文件/网络获取的 JSON 字符串string json_data = "{\"name\":\"JsonCpp\",\"version\":1.0,\"features\":[\"easy\",\"powerful\"]}"; Json::Reader reader; Json::Value root; // 调用 parse 解析,结果存入 rootbool parseResult = reader.parse(json_data, root); if (parseResult) {// 解析成功,访问 root 里的数据cout << "name: " << root["name"].asString() << endl;cout << "version: " << root["version"].asDouble() << endl;// 遍历数组const Json::Value& features = root["features"];for (Json::ArrayIndex i = 0; i < features.size(); ++i) {cout << "feature " << i << ": " << features[i].asString() << endl;}} else {// 解析失败,可打印错误信息(需额外处理,JsonCpp 可获取错误详情 )cerr << "JSON 解析失败!" << endl;}return 0;
}
关键逻辑:
- 先创建
Json::Reader
对象reader
和用于存储结果的Json::Value
对象root
。 - 调用
reader.parse
传入 JSON 字符串json_data
和root
,尝试解析。 - 根据
parse
返回值判断是否成功,成功则通过root
的[]
运算符 +asxxx
函数(如asString
、asDouble
)访问数据;失败可做错误处理。
如果要从文件解析 JSON,示例如下(基于第 3 个 parse
重载 ):
#include <json/json.h>
#include <fstream>
#include <iostream>
using namespace std;int main() {ifstream ifs("test.json"); if (!ifs.is_open()) {cerr << "无法打开文件 test.json" << endl;return -1;}Json::Reader reader;Json::Value root;// 解析文件流bool parseResult = reader.parse(ifs, root); ifs.close();if (parseResult) {// 成功解析,处理 root 数据...cout << "解析文件内容成功,name: " << root["name"].asString() << endl;} else {cerr << "解析文件 JSON 失败!" << endl;}return 0;
}
这里利用 std::ifstream
打开文件,把文件流传给 reader.parse
,实现从文件解析 JSON 。
3.Json::Writer 类:序列化 - 写入
(一)核心作用
Json::Writer
是抽象基类,本身不能直接用,需用它的子类(如 Json::StyledWriter
、Json::FastWriter
),把 Json::Value
对象转换成 JSON 格式的字符串,用于输出到日志、网络、文件等。
(二)常用子类及特点
1. Json::StyledWriter
- 功能:生成格式化、带缩进的 JSON 字符串,可读性强,适合调试、日志打印等场景。
- 示例代码:
Json::Value root;
root["name"] = "StyledWriter";
root["score"] = 95;Json::StyledWriter styled_writer;
// 调用 write 生成格式化 JSON 字符串
string styledJson = styled_writer.write(root); cout << "StyledWriter 输出:\n" << styledJson << endl;
输出效果:
{"name": "StyledWriter","score": 95
}
缩进和换行让 JSON 结构清晰,方便人看。
2. Json::FastWriter
- 功能:生成紧凑、无缩进的 JSON 字符串,体积小,适合网络传输、存储到文件(追求小体积 )等场景。
- 示例代码:
Json::Value root;
root["name"] = "FastWriter";
root["score"] = 95;Json::FastWriter fast_writer;
// 调用 write 生成紧凑 JSON 字符串
string fastJson = fast_writer.write(root); cout << "FastWriter 输出:\n" << fastJson << endl;
输出效果:
{"name":"FastWriter","score":95}
去掉了缩进和多余空格,字符串更短小。
(三)使用示例(结合读写 )
完整演示“解析 JSON 字符串 → 操作数据 → 重新序列化为 JSON 字符串”流程:
#include <json/json.h>
#include <iostream>
#include <string>
using namespace std;int main() {// 1. 准备 JSON 字符串string jsonStr = "{\"name\":\"Original\",\"age\":20}";// 2. 反序列化:用 Json::Reader 解析Json::Reader reader;Json::Value root;reader.parse(jsonStr, root);// 3. 操作 JSON 数据(修改、新增 )root["name"] = "Modified"; root["gender"] = "Male"; // 4. 序列化:用不同 Writer 输出// 4.1 StyledWriter 输出格式化结果Json::StyledWriter styledWriter;string styledResult = styledWriter.write(root);cout << "StyledWriter 结果:\n" << styledResult << endl;// 4.2 FastWriter 输出紧凑结果Json::FastWriter fastWriter;string fastResult = fastWriter.write(root);cout << "FastWriter 结果:\n" << fastResult << endl;return 0;
}
输出结果:
StyledWriter 结果:
{"age": 20,"gender": "Male","name": "Modified"
}
FastWriter 结果:
{"age":20,"gender":"Male","name":"Modified"}