目前在工作中使用到了JSON数据格式,JSON一种轻量的数据交互格式,比XML要简单,主要使用范围不同,JSON适用于数据量小的,
XML可以适用于大规模的数据量,XML的解析很复杂,所以一般开发JSON就可以满足条件。
从JSON的官网上可以看到有很多C的库,例如JSON_checker, LibU, json-parser, json-c等等,试用了好几个,发现有的库实现简单,只有
生成JSON格式的,但没有解析的,导致无法完成服务端接收后解析,生成哈希表等问题。
经过大量的使用最后发现json-c这个库很不错,既可以 生成,也可以解析。 主要说一下解析的函数
首先要创建一个新的的 json object ,编写了几个函数,得到自己想要的返回值
将一个传过来的字符串 生成一个 存放到一个json_object里面,可以认为是初始化方法。
field为集合名字,或者字段标识, 例如: {“age": 32, "name": "xxxx"}, filed 就是指 age或者name这个字段
static struct json_object * json_get_field_object(char *buff, const char *field)
{
struct json_object *new_obj = json_tokener_parse(buff);
return json_object_object_get(new_obj, field);
}
// 实现一个打印各个集合的元素
static void json_print_get_object(struct json_object *obj, const char *field)
{
struct json_object *o = json_object_object_get(obj, field);
printf("%s: %s\n", field, json_object_get_string(o));
}
// 获得一个数组的某个整形字段值
static int json_get_array_field_int(struct json_object *obj, const char *field)
{
struct json_object *o = json_object_object_get(obj, field);
return json_object_get_int(o);
}
// 获得一个数组的某个字符串字段值
static const char * json_get_array_field_string(struct json_object *obj, const char *field)
{
struct json_object *o = json_object_object_get(obj, field);
return json_object_get_string(o);
}
// 得到JSON字符串,可以通过这个得到集合中的数组例如: {”class“:”class2", "room": 302, students [ {"name": "a", "age", 14, "sex": "M"}, {"name": "b", "age", 15, "sex": "M"} ] }
//就可以得到 students这个数组,这个数组又是一个集合,进一步就可以得到集合中的一个学生信息,一个学生信息又是一个集合,进而可以得到具体的数据
static const char * json_get_all_object_to_string(struct json_object *obj, const char *field)
{
struct json_object *o = json_object_object_get(obj, field);
return json_object_get_string(o);
}
//获得一个集合中某一个元素,根据field(整型), 得到这个元素中一个整型字段
static int json_get_array_index_int(struct json_object *obj, int index, const char *field)
{
struct json_object *o = json_object_array_get_idx(obj, index);
return json_get_array_field_int(o, field);
}
//获得一个集合中某一个元素,根据field(字符型), 得到这个元素中一个字符型字段
static char * json_get_array_index_string(struct json_object *obj, int index, const char *field)
{
struct json_object *o = json_object_array_get_idx(obj, index);
return (char *)json_get_array_field_string(o, field);
}
当可以精确的获得每一个字段的时候, 就可以按照想要的方式创建哈希表了。
他这个库中其实提供了一些对数组的操作,并没有完全研究它自身的数组操作,只是通过这种字符串获得对象的方式,也是可以完成的。
以后再看他的数组操作。