struct json_object *my_string, *my_int, *my_object, *my_array; //各种类型的json对象.所有的类型都继承自基类:虚基类
struct json_object *new_obj; //各种类型的json对象.所有的类型都继承自基类:虚基类
my_string = json_object_new_string("\t");
json_object_get_string(my_string) ------------------只对string类型的json_object 操作 返回字符串的指针 char *
json_object_to_json_string(my_string)-------------对任意的json_object 操作,将对象内容转换为一个字符串 并把这个字符串的指针char * 返回!
28 my_string = json_object_new_string("foo");
29 printf("my_string=%s\n", json_object_get_string(my_string));
30 printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));
32 my_int = json_object_new_int(9);
33 printf("my_int=%d\n", json_object_get_int(my_int));
34 printf("my_int.to_string()=%s\n", json_object_to_json_string(my_int));
35
36 /*创建个空json对象----值数组类型*/
37 my_array = json_object_new_array();
38 /*添加jsoni------值类型到数组中*/
39 json_object_array_add(my_array, json_object_new_int(1));
40 json_object_array_add(my_array, json_object_new_int(2));
41 json_object_array_add(my_array, json_object_new_int(3));
42 json_object_array_put_idx(my_array, 4, json_object_new_int(5));
43 printf("my_array=\n");
44 for(i=0; i < json_object_array_length(my_array); i++) {
45 struct json_object *obj = json_object_array_get_idx(my_array, i);
46 printf("\t[%d]=%s\n", i, json_object_to_json_string(obj));
47 }
48 printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));
50 my_object = json_object_new_object();
51 /*添加json名称和值-----键值对----到json对象集合中*/
52 json_object_object_add(my_object, "abc", json_object_new_int(12));
53 json_object_object_add(my_object, "foo", json_object_new_string("bar"));
54 json_object_object_add(my_object, "bool0", json_object_new_boolean(0));
55 json_object_object_add(my_object, "bool1", json_object_new_boolean(1));
56 json_object_object_add(my_object, "baz", json_object_new_string("bang"));
57 /*同样的key 添加会替换掉*/
58 json_object_object_add(my_object, "baz", json_object_new_string("fark"));
59 json_object_object_del(my_object, "baz");
60
61 printf("my_object=\n");
62 /*遍历json对象集合*/
63 json_object_object_foreach(my_object, key, val) {
64 printf("\t%s: %s\n", key, json_object_to_json_string(val));
65 }
66 printf("my_object.to_string()=%s\n", json_object_to_json_string(my_object));
68 /*对些不规则的串做了些解析测试*/
69 new_obj = json_tokener_parse("\"\003\"");
70 printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
71 json_object_put(new_obj);
72
73 new_obj = json_tokener_parse("/* hello */\"foo\"");
74 printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
75 json_object_put(new_obj);
result:
183 my_string=foo
184 my_string.to_string()="foo"
185 my_int=9
186 my_int.to_string()=9
187 my_array=
188 [0]=1
189 [1]=2
190 [2]=3
191 [3]=null
192 [4]=5
193 my_array.to_string()=[ 1, 2, 3, null, 5 ]
194 my_object=
195 abc: 12
196 foo: "bar"
197 bool0: false
198 bool1: true
199 my_object.to_string()={ "abc": 12, "foo": "bar", "bool0": false, "bool1": true }