JSON-C库的使用(2)Json对象的遍历
示例代码:
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <unistd.h> 5 #include "json.h" 6 7 void parseJsonString(struct json_object *obj); 8 9 int main(int argc, char **argv) 10 { 11 const char *json_string = "{\n\ 12 \"errNum\": 0,\n\ 13 \"errMsg\": \"success\",\n\ 14 \"shanghai\": {\n\ 15 \"name\": \"szzs\",\n\ 16 \"curdot\": 2323.554,\n\ 17 \"curprice\": -5.897,\n\ 18 \"rate\": 0.25,\n\ 19 \"dealnumber\": 11586,\n\ 20 \"turnover\": 98322,\n\ 21 },\n\ 22 \"shengzhen\": {\n\ 23 \"name\": \"scz\",\n\ 24 \"curdot\": 2323.554,\n\ 25 \"curprice\": -5.897,\n\ 26 \"rate\": 0.25,\n\ 27 \"dealnumber\": 11586,\n\ 28 \"turnover\": 98322,\n\ 29 },\n\ 30 }"; 31 int ret = 0; 32 struct json_object *obj = NULL; 33 34 printf("%s\n", json_string); 35 obj = json_tokener_parse(json_string); 36 37 parseJsonString(obj); 38 39 if (is_error(obj)) 40 { 41 printf("json_tokener_parse error: %s\n", json_tokener_errors[-(unsigned long )obj]); 42 return -1; 43 } 44 45 if (obj) 46 { 47 json_object_put(obj); 48 obj = NULL; 49 } 50 51 return 0; 52 } 53 54 55 void parseJsonString(struct json_object *obj) 56 { 57 char *key = NULL; 58 struct lh_entry *entry = NULL; 59 struct json_object* val = NULL; 60 61 entry = json_object_get_object(obj)->head; 62 63 while (entry) 64 { 65 key = (char *)entry->k; 66 val = (struct json_object *)entry->v; 67 68 printf("key: %s\n", key); 69 switch (json_object_get_type(val)) 70 { 71 case json_type_null: 72 printf("json type: json_type_null\n"); 73 printf("val: %s\n\n", json_object_get_string(val)); 74 break; 75 76 case json_type_boolean: 77 printf("json type: json_type_boolean\n"); 78 printf("val: %d\n\n", json_object_get_boolean(val)); 79 break; 80 81 case json_type_double: 82 printf("json type: json_type_double\n"); 83 printf("val: %f\n\n", json_object_get_double(val)); 84 break; 85 86 case json_type_int: 87 printf("json type: json_type_int\n"); 88 printf("val: %d\n\n", json_object_get_int(val)); 89 break; 90 91 case json_type_object: 92 printf("json type: json_type_object\n"); 93 printf("val: %s\n\n", json_object_get_string(val)); 94 parseJsonString(val); 95 break; 96 97 case json_type_array: 98 printf("json type: json_type_array\n"); 99 printf("val: %s\n\n", json_object_get_string(val)); 100 break; 101 102 case json_type_string: 103 printf("json type: json_type_string\n"); 104 printf("val: %s\n\n", json_object_get_string(val)); 105 break; 106 107 } 108 109 entry = entry->next; 110 if (NULL == entry) 111 { 112 printf("there is an end\n"); 113 } 114 } 115 }