概要
Json是一种常见的协议,在golang等语言中是集成在标准库里的,但是c++并没有这么做,因此需要引入外部的依赖库。常见的cpp json有json-cpp和rapidjson。本文主要介绍json-cpp库的使用方式。
字符串转换成json格式
Json::Reader reader; // 通过该类型的parse方法来解析字符串成json类型
Json::Value result; // 定义解析后的变量
if (!reader.parse(str, result)) { // str是字符串类型,就是将它转换成json格式
return -1;
}
Golang中转换json字符串时,需要预先定义转换后的结构,如struct,map等,同时可以验证字段的存在性和有效性(validator库)。Json-cpp貌似没有这么强大的功能,但是它也不需要预先定义好数据类型,使用起来更加灵活。
Json value转换成字符串
Json::Value value;// value是一个有赋值的json类型.
string json_str = value.asString()
获取json value中的值
需要区分json value代表什么类型
基础类型
string json_str = value.asString() // string类型
int json_int = value.asInt() // int类型
bool json_bool = value.asBool() // bool类型
float json_float = value.asFloat() // float类型
double json_double = value.asDouble() // double类型
数组类型
Json::Value array; // 它是一个数组类型
for(int i=0; i!=array.size(); i++) { // 遍历数组中的每一个元素
Json::Value value = array[i] // 每个元素也是一个Json::Value类型
}
结构体类型
Json::Value struct_json; // 它是一个结构体类型
Json::Value value = struct_json[“key”]; // 该变量有一个以key为键值的项
类型判断
bool isNull() const; // 是否为空
bool isBool() const; // 是否是bool变量
bool isInt() const;
bool isUInt() const;
bool isIntegral() const;
bool isDouble() const;
bool isNumeric() const;
bool isString() const;
bool isArray() const; // 是否是数组
bool isObject() const; // 是否是结构体
bool isConvertibleTo( ValueType other ) const; // 是否可转换成另一个类型
给json value进行赋值
基础类型
Json::Value post_body;
post_body["product_id"] = product_id_;
post_body["caller_id"] = caller_id_;
post_body["app_version"] = app_version_;
数组类型
Json::Value pois;
std::vector<std::string>& poi_list;
for(auto poi: poi_list) {
pois.append(poi); // 使用append方法添加元素,这里有一个从string类型到Json::Value的隐形转换
}
结构体类型
Json::Value post_body;
Json::Value pois;
post_body["poi_list"] = pois;