C JSON是一種數(shù)字或用花括號(hào)和方括號(hào)創(chuàng)建的數(shù)據(jù)結(jié)構(gòu),它解決了不同編程語言之間的數(shù)據(jù)交換問題。JSON庫用遞歸來打印或構(gòu)建JSON對(duì)象。遞歸就是函數(shù)調(diào)用自身的過程。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <json-c/json.h> static void print_json(json_object *jobj) { enum json_type type; json_object_object_foreach(jobj, key, val) { type = json_object_get_type(val); switch (type) { case json_type_string: printf("string: %s\n", json_object_get_string(val)); break; case json_type_boolean: printf("bool: %s\n", json_object_get_boolean(val) ? "true" : "false"); break; case json_type_int: printf("int: %d\n", json_object_get_int(val)); break; case json_type_object: print_json(val); break; case json_type_array: array_list *alist = json_object_get_array(val); int i; for (i = 0; i< array_list_length(alist); i++) { type = json_object_get_type((json_object*) array_list_get_idx(alist, i)); if (type == json_type_object) print_json((json_object*) array_list_get_idx(alist, i)); else printf("non-object array element: %s\n", json_object_to_json_string((json_object*) array_list_get_idx(alist, i))); } break; default: printf("unknown type: %d\n", type); } } }
在這段代碼中,我們定義了一個(gè)名為print_json的函數(shù)來打印JSON對(duì)象。此函數(shù)使用json_c庫中的json_object_object_foreach函數(shù),其接受兩個(gè)參數(shù):JSON對(duì)象和一個(gè)用于遍歷對(duì)象的回調(diào)函數(shù)。回調(diào)函數(shù)使用以下代碼提取鍵值對(duì):
json_object_get_type(val) json_object_get_string(val) json_object_get_boolean(val) json_object_get_int(val) json_object_get_array(val) json_type_object json_type_array json_object_to_json_string((json_object*) array_list_get_idx(alist, i))
該函數(shù)通過遍歷鍵值對(duì)的列表來打印JSON對(duì)象。如果值是一個(gè)字符串,則會(huì)打印字符串。如果值是布爾值,則會(huì)打印 "true" 或 "false"。如果值是一個(gè)整數(shù),則會(huì)打印整數(shù)。如果值是一個(gè)對(duì)象,則會(huì)遞歸地調(diào)用該函數(shù)來打印該對(duì)象。如果值是一個(gè)數(shù)組,則會(huì)遍歷數(shù)組并打印每個(gè)元素。如果元素是對(duì)象,則會(huì)遞歸地調(diào)用該函數(shù)來打印對(duì)象。否則,將打印元素的JSON字符串表示形式。