【在Linux世界中追寻伟大的One Piece】Jsoncpp|序列化

目录

[1 -> Jsoncpp](#1 -> Jsoncpp)

[1.1 -> 特性](#1.1 -> 特性)

[1.2 -> 安装](#1.2 -> 安装)

[2 -> 序列化](#2 -> 序列化)

[3 -> 反序列化](#3 -> 反序列化)

[4 -> Json::Value](#4 -> Json::Value)


1 -> Jsoncpp

Jsoncpp是一个用于处理JSON数据的C++库。它提供了将JSON数据序列化为字符串以及从字符串反序列化为C++数据结构的功能。Jsoncpp是开源的,广泛用于各种需要处理JSON数据的C++项目中。

1.1 -> 特性

  1. 简单易用:Jsoncpp提供了直观的API,使得处理JSON数据变得简单。
  2. 高性能:Jsoncpp的性能经过优化,能够高效地处理大量JSON数据。
  3. 全面支持:支持JSON标准中的所有数据类型,包括对象、数组、字符串、数字、布尔值和 null。
  4. 错误处理:在解析JSON数据时,Jsoncpp提供了详细的错误信息和位置,方便开发者调试。

当使用Jsoncpp库进行JSON的序列化和反序列化时,确实存在不同的做法和工具类可供选择。以下是对Jsoncpp中序列化和反序列化操作的详细介绍。

1.2 -> 安装

ubuntu:sudo apt-get install libjsoncpp-dev
Centos: sudo yum install jsoncpp-devel

2 -> 序列化

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

1. 使用Json::Value的toStyledString方法:

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

示例:

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS 1

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

int main()
{
	Json::Value root;
	root["name"] = "joe";
	root["sex"] = "男";
	std::string s = root.toStyledString();
	std::cout << s << std::endl;
	return 0;
}

$ . / test.exe
{
"name" : "joe",
"sex" : "男"
}

2. 使用Json::StreamWriter:

优点:提供了更多的定制选项,如缩进、换行符等。

示例:

cpp 复制代码
#include <iostream>
#include <string>
#include <sstream>
#include <memory>
#include <jsoncpp/json/json.h>

int main()
{
	Json::Value root;
	root["name"] = "joe";
	root["sex"] = "男";
	Json::StreamWriterBuilder wbuilder; // StreamWriter 的工厂

	std::unique_ptr<Json::StreamWriter>
	writer(wbuilder.newStreamWriter());

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

	std::cout << ss.str() << std::endl;

	return 0;
}
$ . / test.exe
{
"name" : "joe",
"sex" : "男"
}

3. 使用Json::FastWriter:

优点:比StyledWriter更快,因为它不添加额外的空格和换行符。

示例:

cpp 复制代码
#include <iostream>
#include <string>
#include <sstream>
#include <memory>
#include <jsoncpp/json/json.h>

int main()
{
	Json::Value root;
	root["name"] = "joe";
	root["sex"] = "男";

	// Json::FastWriter writer;
	Json::StyledWriter writer;

	std::string s = writer.write(root);
	std::cout << s << std::endl;

	return 0;
}

$ . / test.exe
{
"name" : "joe",
"sex" : "男"
}

3 -> 反序列化

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

1. 使用Json::Reader:

优点:提供详细的错误信息和位置,方便调试。

示例:

cpp 复制代码
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>

int main() 
{
	// JSON 字符串
	std::string json_string = "{\"name\":\"张三\",
		\"age\":30, \"city\":\"北京\"}";

	// 解析 JSON 字符串
	Json::Reader reader;
	Json::Value root;

	// 从字符串中读取 JSON 数据
	bool parsingSuccessful = reader.parse(json_string, root);
	if (!parsingSuccessful) {
		// 解析失败,输出错误信息
		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;
}

$ . / test.exe
Name : 张三
Age : 30
City : 北京

2. 使用Json::CharReader 的派生类:

在某些情况下,你可能需要更精细地控制解析过程,可以直接使用Json::CharReader的派生类。

但通常情况下,使用Json::parseFromStream或Json::Reader的parse方法就足够了。

总结:

  • toStyledString、StreamWriter和FastWriter提供了不同的序列化选项,你可以根据具体需求选择使用。
  • Json::Reader和parseFromStream函数是Jsoncpp中主要的反序列化工具,它们提供了强大的错误处理机制。
  • 在进行序列化和反序列化时,请确保处理所有可能的错误情况,并验证输入和输出的有效性。

4 -> Json::Value

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

1. 构造函数

  • **Json::Value():**默认构造函数,创建一个空的Json::Value对象。
  • **Json::Value(ValueType type,bool allocated = false):**根据给定的ValueType(如nullValue,intValue,stringValue等)创建一个Json::Value对象。

2. 访问元素

  • **Json::Value& operator[](const char* key):**通过键(字符串)访问对象中的元素。如果键不存在,则创建一个新的元素。
  • **Json::Value& operator[](const std::string& key):**同上,但使用std::string类型的键。
  • **Json::Value& operator[](ArrayIndex index):**通过索引访问数组中的元素。如果索引超出范围,则创建一个新的元素。
  • **Json::Value& at(const char* key):**通过键访问对象中的元素,如果键不存在则抛出异常。
  • **Json::Value& at(const std::string& key):**同上,但使用std::string类型的键。

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():**检查值是否为对象(即键值对的集合)。

4. 赋值和类型转换

  • **Json::Value& operator=(bool value):**将布尔值赋给Json::Value对象。
  • **Json::Value& operator=(int value):**将整数赋给Json::Value对象。
  • **Json::Value& operator=(unsigned int value):**将无符号整数赋给Json::Value对象。
  • **Json::Value& operator=(Int64 value):**将64位整数赋给Json::Value对象。
  • **Json::Value& operator=(UInt64 value):**将64位无符号整数赋给Json::Value 对象。
  • **Json::Value& operator=(double value):**将双精度浮点数赋给Json::Value对象。
  • **Json::Value& operator=(const char* value):**将C字符串赋给Json::Value对象。
  • **Json::Value& operator=(const std::string& value):**将std::string赋给Json::Value对象。
  • **bool asBool():**将值转换为布尔类型(如果可能)。
  • **int asInt():**将值转换为整数类型(如果可能)。
  • **Int64 asInt64():**将值转换为64位整数类型(如果可能)。
  • **unsigned int asUInt():**将值转换为无符号整数类型(如果可能)。
  • **UInt64 asUInt64():**将值转换为64位无符号整数类型(如果可能)。
  • **double asDouble():**将值转换为双精度浮点数类型(如果可能)。
  • **std::string asString():**将值转换为字符串类型(如果可能)。

5. 数组和对象操作

  • **size_t size():**返回数组或对象中的元素数量。
  • **bool empty():**检查数组或对象是否为空。
  • **void resize(ArrayIndex newSize):**调整数组的大小。
  • **void clear():**删除数组或对象中的所有元素。
  • **void append(const Json::Value& value):**在数组末尾添加一个新元素。
  • **Json::Value& operator[](const char* key, const Json::Value&defaultValue = Json::nullValue):**在对象中插入或访问一个元素,如果键不存在则使用默认值。
  • **Json::Value& operator[](const std::string& key, constJson::Value& defaultValue = Json::nullValue):**同上,但使用std::string类型的。

感谢各位大佬支持!!!

互三啦!!!

相关推荐
叶凡要飞5 分钟前
linux安装google chrome 谷歌浏览器
linux·运维·chrome
清静诗意6 分钟前
在 Ubuntu 上通过 Docker 与 Docker Compose 部署项目的完整指南
linux·ubuntu·docker
企鹅虎28 分钟前
linux内核驱动开发视频课程
linux
专注VB编程开发20年1 小时前
vb.net编写DDE(Dynamic Data Exchange)服务器
运维·服务器·github·vb.net·dde
Clownseven1 小时前
如何用Fail2ban保护Linux服务器?防止SSH暴力破解教程
linux·服务器·ssh
源码部署21 小时前
linux内核驱动开发视频课程
linux
chaofan9802 小时前
如何用 Claude Code 搭建安全、可测、可自动化的 GitHub CI 流程?
运维·人工智能·ci/cd·ai·自动化·github·claude
无敌最俊朗@2 小时前
Linux 进程创建与控制详解
linux·运维·服务器
迎風吹頭髮2 小时前
UNIX下C语言编程与实践8-UNIX 静态库原理与创建:ar 命令的使用与静态库调用全流程
服务器·c语言·unix
张红尘2 小时前
龙蜥OS8.10配置repo源使用RPM安装Redis8.2
linux·redis·操作系统