1,引入
① 最近学习了libjson-c库解析json格式类型的字符串,把用到的一下库函数总结一下,方便查看。
② 同时我们要理解一下引用计数,初始化对象时为1,当引用计数为0时,内存将被释放,同时,在遍历对象中的键值时,返回的指针地址,不要保存,因为在下次遍历时,指针的地址不一定是这个存储的值,有可能有变化,使用我们取值时,需要另存一份.
如:strcpy or strdup等
调用的头文件为:#include <json-c/json.h>
2,用到的API
#json格式解析函数
json_object *root = NULL;
root = json_tokener_parse(str);
# 该函数接收json类型的字符串,内部解析后,返回json_object 结构
# json对象的格式判断和类型获取
struct json_object *d_obj = NULL;
//判断json_object当前是什么类型的值
json_object_is_type(d_obj, json_type_array);
//获取当前json-object当前类型
json_object_get_type(d_obj);
# 一般用的比较多的是 json_object_get_xxx
json_object_get_string
json_object_get_int
...
# 获取键对应的值数据
const json_object *code_obj = NULL;
json_object_object_get_ex(head, name, &code_obj)
注:
head : 为刚刚我们解析到的root
name : 为当前root所在层的键名
code_obj : 为json_object 对象值
例子:
char *p =
{
"data" : "heallo",
"code" : -1,
"list" : {
"good": "OK"
}
};
root = json_tokener_parse(p);
if (json_object_object_get_ex(root, "code", &code_obj)) {
int code = json_object_get_int(code_obj);
printf("code = %d\n", code);
}
注意:这里name我们只能传递data or code,不能传递good
字符串数组一般解析流程:
如: ["h1","h2","h3","h4"]
int parase_array_info(const json_object *head, char *name)
{
int i =0, index = 0;
int array_len = 0;
char *ptr = NULL;
struct json_object *elem = NULL;
struct json_object *datalist_obj = NULL;
//从head中获取name是这个值
if (json_object_object_get_ex(head, name, &datalist_obj)) {
//判断是不是数组类型
if (!json_object_is_type(datalist_obj, json_type_array)) {
return -1;
}
//获取数组的长度
array_len = json_object_array_length(datalist_obj);
if (array_len <= 0) {
return -1;
} else {
for (i = 0; i < array_len; i++) {
//循环遍历数组中的元素
elem = json_object_array_get_idx(datalist_obj, i);
if (elem != NULL) {
ptr = json_object_get_string(elem);
if(ptr) {
printf("i = %d, p = %s\n", i, ptr);
}
elem = NULL;
}
}
}
return 0;
}
return -1;
}
内存的释放?我上面用到的函数,和内部的临时变量,都不需要释放内存,我们只需要释放
json_object_put(root); //释放最开始解析到的json_object就行
3,关于生成一个json数组
int crete_json_str()
{
//创建一个root对象
struct json_object *root = json_object_new_object();
//向root中加入以下键值对
json_object_object_add(root, "name", json_object_new_string("Alice"));
json_object_object_add(root, "age", json_object_new_int(30));
json_object_object_add(root, "is_student", json_object_new_boolean(0)); // false
//创建地址对象
struct json_object *address = json_object_new_object();
//向address中加入以下键值对
json_object_object_add(address, "city", json_object_new_string("Beijing"));
json_object_object_add(address, "zip", json_object_new_int(100000));
//把这个addrees加入root中
json_object_object_add(root, "address", address);
//打印当前json字符串
const char *json_str = json_object_to_json_string(root);
printf("Generated JSON:\n%s\n", json_str);
//释放
json_object_put(root);
}
注意: 释放时由于address已经加入到root中,可以理解为address已经被root接管,如果我们free时,只需要free掉root就行,如果没有调用json_object_object_add(root, "address", address);
那最后free时,就需要多加一次 json_object_put(address);
4,遍历一个对象的所以键值对
# 这是一个宏定义
json_object_object_foreach(obj, key, val) {
# key 是键
# val 是该键对应的值
}
5,总结
学习了libjson-c的一些调用,能帮助我解析特定类型的json字符串,也参考了很多人写的blog和AI,希望有帮助