一、介绍
1、作用
用于数据交换
2、结构
对象:由一些键值对组成,用 {} 包围
数组:键值对中值的一种,包含一系列数据,用 [] 包围
值:可以是字符串,数字,对象,数组,布尔值和 NULL
3、语法
键值对以 "key": value 出现
多个键之间用 , 分隔
所有键必须是字符串,用 "" 包围
4、使用
(1)包含头文件
#include <gflags/gflags.h>
(2)makefile 链接
g++ main.cc -o main -ljsoncpp
(3)数据转储类 Json::Value
用于中间数据的转化:多个数据存入 Value 进行序列化,对于字符串反序列化之后的值存入 Value
namespace Json {
enum ValueType {
nullValue = 0, ///< 'null' value
intValue, ///< signed integer value
uintValue, ///< unsigned integer value
realValue, ///< double value
stringValue, ///< UTF-8 string value
booleanValue, ///< bool value
arrayValue, ///< array value (ordered list)
objectValue ///< object value (collection of name/value pairs).
};
class JSON_API Value {
public:
void swap(Value& other);
void copy(const Value& other);
const char* asCString() const;
String asString() const;
Int asInt() const;
UInt asUInt() const;
Int64 asInt64() const;
UInt64 asUInt64() const;
float asFloat() const;
double asDouble() const;
bool asBool() const;
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;
// Array-API
ArrayIndex size() const;
bool empty() const;
void clear();
void resize(ArrayIndex newSize);
Value& operator[](ArrayIndex index);
Value& append(const Value& value);
Value& operator[](const char* key);
Value& operator[](const String& key);
void removeMember(const String& key);
bool isMember(const String& key) const;
String toStyledString() const;
} }
(4)重要接口
[] 重载:Json::Value val; val[key] = value
append 数组添加元素:val[key].append(value1);
value 获取:as...接口,auto value = val[key].asString();
数组元素获取:auto value = cal[key][0].asInt();
各种判断 key 对应 value 类型:isNull(), isArray(), isObject()
序列化 Json::Value:String tiStyleString();
二、代码案例
1、普通操作


2、序列化操作
namespace Json {
class JSON_API StreamWriter {
public:
virtual int write(Value const& root, OStream* sout)
class JSON_API Factory {
public:
virtual StreamWriter* newStreamWriter();
}
};
String JSON_API writeString(
StreamWriter::Factory const& factory,
Value const& root);
class streamWriterBuilder : public StreamWriter::Factory {
public:
Json::Value settings_;
};
}
先实例化建造者 streamWriterBuilder ,然后构造序列化对象 StreamWriter ,最后序列化

![]()
3、反序列化操作
namespace Json {
class JSON_API CharReader {
public:
virtual bool parse(
char const* beginDoc,
char const* endDoc,
Value* root,
String* errs) = 0;
class JSON_API Factory {
virtual CharReader* newCharReader() const = 0;
};
};
class JSON_API CharReaderBuilder : public CharReader::Factory {
public:
Json::Value settings_;
CharReader* newCharReader() const override;
};
}
流程一样


11万+

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



