示例代码:
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 = "{ 12 "errNum": 0, 13 "errMsg": "success", 14 "shanghai": { 15 "name": "szzs", 16 "curdot": 2323.554, 17 "curprice": -5.897, 18 "rate": 0.25, 19 "dealnumber": 11586, 20 "turnover": 98322, 21 }, 22 "shengzhen": { 23 "name": "scz", 24 "curdot": 2323.554, 25 "curprice": -5.897, 26 "rate": 0.25, 27 "dealnumber": 11586, 28 "turnover": 98322, 29 }, 30 }"; 31 int ret = 0; 32 struct json_object *obj = NULL; 33 34 printf("%s ", 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 ", 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 ", key); 69 switch (json_object_get_type(val)) 70 { 71 case json_type_null: 72 printf("json type: json_type_null "); 73 printf("val: %s ", json_object_get_string(val)); 74 break; 75 76 case json_type_boolean: 77 printf("json type: json_type_boolean "); 78 printf("val: %d ", json_object_get_boolean(val)); 79 break; 80 81 case json_type_double: 82 printf("json type: json_type_double "); 83 printf("val: %f ", json_object_get_double(val)); 84 break; 85 86 case json_type_int: 87 printf("json type: json_type_int "); 88 printf("val: %d ", json_object_get_int(val)); 89 break; 90 91 case json_type_object: 92 printf("json type: json_type_object "); 93 printf("val: %s ", json_object_get_string(val)); 94 parseJsonString(val); 95 break; 96 97 case json_type_array: 98 printf("json type: json_type_array "); 99 printf("val: %s ", json_object_get_string(val)); 100 break; 101 102 case json_type_string: 103 printf("json type: json_type_string "); 104 printf("val: %s ", 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 "); 113 } 114 } 115 }