C++ Jsoncpp 常用技巧
- Json對象循環周遊
- Array數組循環周遊
- char*轉Json
- Json轉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"}