代码样式
int main() { Json::Value json_value = Json::Value(Json::objectValue); json_value["object_one"] = 1; json_value["object_two"] = 2; json_value["object_three"] = 3; json_value["object_a"] = 4; Json::Value::Members mem = json_value.getMemberNames(); for (Json::Value::Members::iterator iter = mem.begin(); iter != mem.end(); ++iter) { cout << *iter << " : " << json_value[*iter]; } return 0; }运行结果
object_a : 4 object_one : 1 object_three : 3 object_two : 2总结:使用迭代器去遍历Json对象时,会按照key的值排序进行输出,而不是按照添加key_value的顺序输出;
代码样式
int main() { Json::Value json_value = Json::Value(Json::arrayValue); json_value.append(1); json_value.append(2); json_value.append(4); json_value.append(3); json_value.append(5); for (unsigned int i = 0;i<json_value.size();++i){ cout << json_value[i].asInt(); if(i != json_value.size()-1){ cout << ","; } } cout << endl; cout << "+++++++++++++++++++++++++++++++" << endl; for (unsigned int i = 0;i<json_value.size();++i){ cout << json_value[i]; if(i != json_value.size()-1){ cout << ","; } } cout << endl; return 0; }运行结果
1,2,4,3,5 +++++++++++++++++++++++++++++++ 1 ,2 ,4 ,3 ,5总结:遍历Json数组时一定要将元素通过asInt()、asString()转成你需要的数据类型,否之直接使用会出现意想不到的问题;
代码样式
int main() { char* json_str = "{\"object\":[1,2,3]}"; cout << json_str << endl; cout << "===== change to json =====" << endl; Json::Value json_value; Json::Reader json_reader; json_reader.parse(json_str,json_value); cout << json_value << endl; return 0; }运行结果
{"object":[1,2,3]} ===== change to json ===== { "object" : [ 1, 2, 3 ] }代码样式
int main() { Json::Value json_value; json_value["object"] = "json_test"; cout << json_value << endl; cout << "===== change to char* =====" << endl; string json_str; Json::FastWriter jsonWriter; json_str = jsonWriter.write(json_value); cout << json_str << endl; return 0; }运行结果
{ "object" : "json_test" } ===== change to char* ===== {"object":"json_test"}