JSON-C库安装
# 安装工具
sudo apt install git
sudo apt install autoconf automake libtool
sudo apt install valgrind # optional
# 下载源码
wget https://github.com/json-c/json-c/archive/json-c-0.14-20200419.tar.gz -O json-c.tar.gz
tar zxvf json-c.tar.gz
mv json-c-json-c-0.14-20200419 json-c
# 编译安装
mkdir json-c-build && cd json-c-build
cmake ../json-c
make
make test
make USE_VALGRIND=0 test
make install
# 至此安装成功
# 头文件目录
/usr/local/include
# 动态库目录
/lib/x86_64-linux-gnu 或者 /usr/local/lib
# 合法的json实例
{"name":"jack","sex":"male"}
{"name":"jack","age":18,"address":{"country":"china","zip-code":"100000"}}
{"a":1,"b":[1,2,3]}
JSON-C库的使用
// 将符合json格式的字符串构造为一个json对象
struct json_object *json_tokener_parse(const char *);
// 将json对象内容,转成json格式的字符串
const char *json_object_to_json_string(struct json_object *obj);
// 创建json对象
struct json_object *json_object_new_object();
// 往json独享中添加键值对
void json_object_object_add(struct json_object *obj,const char *key,struct json_object *value);
// 将C字符串转换为JSON字符串格式的对象
struct json_object *json_object_new_string(const char *s);
// 将整数转换为JSON格式的对象
struct json_object *json_object_new_int(int32_t i);
// 获取json对象的整形数值
int32_t json_object_get_int(struct json_object *obj);
// 获取json对象的字符串值
const char *json_object_get_string(struct json_object *obj);
// 解析json分为两步:
// 第一步:根据键名,从json对象中获取对应数据的json对象
// 第二步:根据数据类型,将数据对应的json对象转化为对应类型的数据
// 根据键名获取对应的json对象
json_bool json_object_object_get_ex(struct json_object *obj,const char *key,struct json_object **value);
// 参数:obj源json对象,key键名,value用于存放获取的对应数据的json对象,注意这里一定传入的是二级指针,不用传入实体
// 获取json对象的类型 类型有:json_type_null json_type_boolean json_type_double json_type_int json_type_object json_type_array json_type_string
json_type json_object_get_type(struct json_object *obj);
// 数组类型相关操作(json_type_array类型)
// 创建一个JSON数组类型JSON对象
struct json_object *json_object_new_array(void);
// 往json_type_array类型的json对象中添加一个元素
int json_object_array_add(struct json_object *obj,struct json_object *val);
// 获取json_type_array类型的json对象中指定下标的元素
struct json_object *json_object_array_get_idx(struct json_object *obj,int idx);
注意:编译时要加上动态库,例如:gcc -o build main.c -ljson-c