C++ Jsoncpp 常用技巧

    xiaoxiao2024-12-25  65

    C++ Jsoncpp 常用技巧

    Json对象循环遍历Array数组循环遍历char*转JsonJson转string

    Json对象循环遍历

    代码样式

    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的顺序输出;

    Array数组循环遍历

    代码样式

    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()转成你需要的数据类型,否之直接使用会出现意想不到的问题;

    char*转Json

    代码样式

    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 ] }

    Json转string

    代码样式

    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"}
    最新回复(0)