Jsoncpp简单使用

Jsoncpp是个跨平台的C++开源库,提供的类为我们提供了很便捷的操作,而且使用的人也很多。在使用之前我们首先要从github仓库下载源码,地址如下:GitHub - open-source-parsers/jsoncpp: A C++ library for interacting with JSON.

文档地址:https://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html


jsoncpp库中的类被定义到了一个Json命名空间中。

使用jsoncpp库解析json格式的数据,需要掌握三个类:

  1. Value 类:将json支持的数据类型进行了包装,最终得到一个Value类型
  2. FastWriter类:将Value对象中的数据序列化为字符串
  3. Reader类:反序列化, 将json字符串 解析成 Value 类型

Value -> 对Json支持的数据类型进行封装/解析

// Json支持的数据类型
Type = {int, double, float, string, char*, bool, JsonArray, JsonObject}
// 构造函数
  Value(ValueType type = nullValue);
  Value(Int value);
  Value(UInt value);
#if defined(JSON_HAS_INT64)
  Value(Int64 value);
  Value(UInt64 value);
#endif // if defined(JSON_HAS_INT64)
  Value(double value);
  Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
  Value(const char* begin, const char* end);

// 将Value对象转换成对应类型的数据
  Int asInt() const;
  UInt asUInt() const;
#if defined(JSON_HAS_INT64)
  Int64 asInt64() const;
  UInt64 asUInt64() const;
#endif // if defined(JSON_HAS_INT64)
  LargestInt asLargestInt() const;
  LargestUInt asLargestUInt() const;
  float asFloat() const;
  double asDouble() const;
  bool asBool() const;

// 判断Value对象中存储的数据的类型
  bool isNull() const;
  bool isBool() const;
  bool isInt() const;
  bool isInt64() const;
  bool isUInt() const;
  bool isUInt64() const;
  bool isIntegral() const;
  bool isDouble() const;
  bool isNumeric() const;
  bool isString() const;
  bool isArray() const;
  bool isObject() const;

// 取值 
// 格式化 -> 将对象转换为字符串
// 适合于查看信息或者写文件
std::string toStyledString() const;

Reader

// json格式字符串 -> Value对象
// c++
bool parse(const std::string& document, Value& root, bool collectComments = true);
	参数:
		- document: json字符串, 传入参数
		- root: 传出参数, 转换完成之后的Value对象
// c用法
bool parse(const char* beginDoc, const char* endDoc, 
           Value& root, bool collectComments = true);
	参数:
		- beginDoc: 字符串起始地址
		- endDoc: 字符串结束地址
		- root: 传出参数, 转换完成之后的Value对象
// c++用法
bool parse(std::istream& is, Value& root, bool collectComments = true);
	参数:
		- is: 文件流对象, 使用这个流对象打开一个磁盘文件
		- root: 传出参数, 转换完成之后的Value对象

FastWriter

// 将Value对象中的数据格式化 -> 字符串
// 适合于网络数据的发送
// 得到的字符串中没有换行符
std::string write(const Value& root);

// 得到这个返回值:
	- 写磁盘 -> 写到配置文件中
	- 网络传参数

 

旧API使用方法参考   jsoncpp的编译和使用 | 爱编程的大丙

新API使用方法参考(new出内存,新的API如果反复调用的话会产生大量内存碎片)

C++ JSON 库 jsoncpp 新API的使用方法(CharReaderBuilder / StreamWriterBuilder)_jsoncpp charreader-CSDN博客 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值