1、封装json
假设想将:hello, 封装成:{“result”:“hello”}
const static string RESPONSE_KEY = "result";
Json::Value val;
val[RESPONSE_KEY] = "hello";
Json::FastWriter json_writer;
json_output = json_writer.write(val);
- 其他特殊用法
封装成 {“result”:[]}
Json::Value val;
val["result"].resize();
封装成 {“result”:{}}
Json::Value val;
Json::Value val1(Json::objectValue);
val["result"] = val;
2、解析json
假设想将:{“result”:“hello”}解析,代码如下:
const static string RESPONSE_KEY = "result";
Json::Reader reader;
Json::Value value;
if (!reader.parse(json_input, value)) {
std::cout<<"input parse failure"<<std::endl;
return -1;
}
try {
data_obj.m_sQuery_ = value[RESPONSE_KEY].asString();
}
catch (...) {
std::cout<<"input throw exception"<<std::endl;
return -2;
}
其他:常用方法或用法总结
//1、对象转字符串
data_value.toStyledString()
//2、查看当前key是否为json中的键
data_value.isMember(key)
//3、循环遍历json中的数据(在不知key的情况或者array)
//https://blog.csdn.net/hellokandy/article/details/51607311
//4、array拼接
data_value.append(value)
//示例:https://blog.csdn.net/abcd1f2/article/details/51438818