C語言中的json通信技術現在已經被廣泛應用于網絡通信、數據傳輸等方面。在C語言中,我們可以使用json-c這一開源庫來實現對json數據的解析和生成。
#include#include int main() { // 生成json對象 struct json_object *obj = json_object_new_object(); struct json_object *subobj = json_object_new_object(); json_object_object_add(obj, "name", json_object_new_string("hello")); json_object_object_add(obj, "age", json_object_new_int(18)); json_object_object_add(subobj, "language", json_object_new_string("C")); json_object_object_add(obj, "skill", subobj); // 將json對象轉為字符串 const char *str = json_object_to_json_string(obj); printf("%s\n", str); // 解析json字符串 struct json_object *newobj = json_tokener_parse(str); struct json_object *name_obj, *age_obj, *skill_obj, *language_obj; json_object_object_get_ex(newobj, "name", &name_obj); json_object_object_get_ex(newobj, "age", &age_obj); json_object_object_get_ex(newobj, "skill", &skill_obj); json_object_object_get_ex(skill_obj, "language", &language_obj); printf("name = %s, age = %d, skill = %s\n", json_object_get_string(name_obj), json_object_get_int(age_obj), json_object_get_string(language_obj)); // 釋放內存 json_object_put(obj); json_object_put(newobj); return 0; }
上面這段代碼演示了對json數據的生成和解析過程。我們可以通過json_object_new_*系列函數創建json對象,然后通過json_object_object_add函數將其添加到json對象中,最后使用json_object_to_json_string函數將json對象轉換成字符串。對于解析json字符串,我們可以使用json_tokener_parse函數將其轉換成json對象后,再使用json_object_object_get_ex函數獲取鍵值對應的值。