C語(yǔ)言可以通過(guò)JSON庫(kù)來(lái)獲取JSON對(duì)象和值。
首先需要在代碼中包含json-c.h頭文件:
#include <json-c/json.h>
接下來(lái),通過(guò)以下代碼將JSON字符串解析成JSON對(duì)象:
const char *json_string = "{\"name\":\"張三\",\"age\":23}"; struct json_object *json_obj = json_tokener_parse(json_string);
通過(guò)使用json_object_object_get函數(shù)可以獲取JSON對(duì)象中的鍵值對(duì),例如:
int age = 0; json_object *json_age = json_object_object_get(json_obj, "age"); if (json_age) { age = json_object_get_int(json_age); }
通過(guò)使用json_object_array_get_idx函數(shù)可以獲取JSON數(shù)組中的元素,例如:
const char *json_array_string = "[{\"name\":\"張三\",\"age\":23},{\"name\":\"李四\",\"age\":24}]"; struct json_object *json_array = json_tokener_parse(json_array_string); int array_len = json_object_array_length(json_array); for (int i = 0; i < array_len; i++) { json_object *json_obj = json_object_array_get_idx(json_array, i); json_object *json_name = json_object_object_get(json_obj, "name"); json_object *json_age = json_object_object_get(json_obj, "age"); const char *name = json_object_get_string(json_name); int age = json_object_get_int(json_age); }
最后,通過(guò)使用json_object_put函數(shù)釋放內(nèi)存:
json_object_put(json_obj); json_object_put(json_array);