Jsoncpp

1.Jsoncpp简介 

Jsoncpp 是一个用于处理 JSON 数据的 C++ 库。它提供了将 JSON 数据序列化为字符串以及从字符串反序列化为 C++ 数据结构的功能。Jsoncpp 是开源的,广泛用于各种需要处理 JSON 数据的 C++ 项目中。
特性:
1. 简单易用:Jsoncpp 提供了直观的 API,使得处理 JSON 数据变得简单。
2. 高性能:Jsoncpp 的性能经过优化,能够高效地处理大量 JSON 数据。
3. 全面支持:支持 JSON 标准中的所有数据类型,包括对象、数组、字符串、数字、布尔值和null
4. 错误处理:在解析 JSON 数据时,Jsoncpp 提供了详细的错误信息和位置,方便 开发者调试。  
当使用 Jsoncpp 库进行 JSON 的序列化和反序列化时,确实存在不同的做法和工具类
可供选择。以下是对 Jsoncpp 中序列化和反序列化操作的详细介绍:
安装
ubuntu:sudo apt-get install libjsoncpp-dev
Centos: sudo yum install jsoncpp-devel

2. Json::Value

Json::Value 是 Jsoncpp 库中的一个重要类,用于表示和操作 JSON 数据结构。以下是一些常用的 Json::Value 操作:

2.1 构造函数

Json::Value()	创建空值(null 类型)
Json::Value(ValueType type)	指定类型创建(如 intValue, stringValue)
Json::Value(int value)	直接构造整数类型值
Json::Value(const char* value)	直接构造字符串类型值
Json::Value nullVal;          // null
Json::Value intVal(42);       // 整数
Json::Value strVal("hello");  // 字符串

2.2 访问元素

对象访问

operator[](const char*)	通过键访问(自动创建不存在的键)
at(const char*)	通过键访问(不存在时抛出异常)
get(const char*, const Value& default)	安全访问(带默认值)
Json::Value obj;
obj["name"] = "Alice";  // 自动创建
std::string name = obj.at("name").asString();  // 安全访问
int age = obj.get("age", Json::Value(18)).asInt();

数组访问

operator[](ArrayIndex)	通过索引访问(自动扩展数组)
append(const Value&)	向数组末尾添加元素
Json::Value arr;
arr.append(1);
arr.append("two");
int first = arr[0].asInt();  // 获取第一个元素

2.3 类型检查

bool isNull():检查值是否为 null。
bool isBool():检查值是否为布尔类型。
bool isInt():检查值是否为整数类型。
bool isInt64():检查值是否为 64 位整数类型。
bool isUInt():检查值是否为无符号整数类型。
bool isUInt64():检查值是否为 64 位无符号整数类型。
bool isIntegral():检查值是否为整数或可转换为整数的浮点数。
bool isDouble():检查值是否为双精度浮点数。
bool isNumeric():检查值是否为数字(整数或浮点数)。
bool isString():检查值是否为字符串。
bool isArray():检查值是否为数组。
bool isObject():检查值是否为对象(即键值对的集合)。

2.4 类型转换

bool asBool():将值转换为布尔类型(如果可能)。
int asInt():将值转换为整数类型(如果可能)。
Int64 asInt64():将值转换为 64 位整数类型(如果可能)。
unsigned int asUInt():将值转换为无符号整数类型(如果可能)。
UInt64 asUInt64():将值转换为 64 位无符号整数类型(如果可能)。
double asDouble():将值转换为双精度浮点数类型(如果可能)。
std::string asString():将值转换为字符串类型(如果可能)

2.5 对象操作

size_t size():返回数组或对象中的元素数量。
bool empty():检查数组或对象是否为空。
void resize(ArrayIndex newSize):调整数组的大小。
void clear():删除数组或对象中的所有元素。
void append(const Json::Value& value):在数组末尾添加一个新元素。

2.6核心序列化/反序列化工具

Json::Reader	旧版 JSON 解析器(已弃用,建议用 CharReader)
Json::CharReader	新版 JSON 解析器(配合 CharReaderBuilder 使用)
Json::CharReaderBuilder	配置和创建 CharReader 的工厂类
Json::FastWriter	生成紧凑格式(无缩进)JSON 字符串
Json::StyledWriter	生成美化格式(带缩进)JSON 字符串
Json::StreamWriter	可定制的 JSON 生成器(配合 StreamWriterBuilder 使用)
Json::StreamWriterBuilder	配置和创建 StreamWriter 的工厂类

3. 序列化

序列化指的是将数据结构或对象转换为一种格式,以便在网络上传输或存储到文件中。Jsoncpp 提供了多种方式进行序列化:

3.1 Json::Value 的 toStyledString 方法

将 Json::Value 对象直接转换为格式化的 JSON 字符串

示例:

#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>

int main()
{
    Json::Value root; // 创建根节点
    root["name"] = "jack"; // 添加字符串字段
    root["age"] = "18";
    std::string s = root.toStyledString();

    std::cout << s << std::endl;
    return 0;
}

2.2 Json::FastWriter

优点:比 StyledWriter 更快,因为它不添加额外的空格和换行符。
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>

int main()
{
    Json::Value root;
    root["name"] = "Jack";
    root["age"] = "18";

    Json::FastWriter fwriter;
    std::string s = fwriter.write(root);

    std::cout << s << std::endl;
}

2.3  Json::StreamWriter

优点:提供了更多的定制选项,如缩进、换行符等。
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>

int main()
{
    Json::Value root;
    root["name"] = "Jack";
    root["age"] = "18";

    Json::StreamWriterBuilder wbuilder;
    wbuilder["indentation"] = "  "; // 设置缩进
    std::unique_ptr<Json::StreamWriter> writer(wbuilder.newStreamWriter());

    std::stringstream ss;
    writer->write(root, &ss);

    std::cout << ss.str() << std::endl;
    return 0;
}

StreamWriterBuilder():用于配置 JSON 输出的格式(如缩进、编码等)。

newStreamWrite():生成一个 StreamWriter 实例,用于将 Json::Value 写入输出流。

writer->write():将 Json::Value 对象(root)写入输出流(ss)。

未设置缩进:

设置缩进:

4. 反序列化

反序列化指的是将序列化后的数据重新转换为原来的数据结构或对象Jsoncpp 提供了以下方法进行反序列化:

Json::Reader

优点:提供详细的错误信息和位置,方便调试。
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>

int main()
{
    // 定义json字符串
    std::string json_string = "{\"name\":\"Jack\", \"age\":30, \"city\":\"北京\"}";

    Json::Value root;
    Json::Reader reader;

    bool prasesuccess = reader.parse(json_string, root);
    if (!prasesuccess)
    {
        std::cout << "Failed to parse JSON: " << reader.getFormattedErrorMessages() << std::endl;
        return 1;
    }

    // 访问Json数据
    std::string name = root["name"].asString();
    int age = root["age"].asInt();
    std::string city = root["city"].asString();
    // 输出结果
    std::cout << "Name: " << name << std::endl;
    std::cout << "Age: " << age << std::endl;
    std::cout << "City: " << city << std::endl;
    
    return 0;
}
 - reader.parse() 方法将 JSON 字符串解析为 Json::Value 对象(root)。
 - root["key"]:访问 JSON 对象中的字段。
 - .asString()、.asInt():将字段值转换为 C++ 类型。
注意:如果类型不匹配(如对非数字字段调用 asInt()),会返回默认值(0 或空字符串)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值