之前做项目的时候,在嵌入式端侧用到了json数据格式,主要负责和服务器通信使用。json-c网上的资料很少,所以下面总结一些,再附上一些代码,供大家参考使用。
json-c安装:
apt-get install libjson0-dev
libjson0-dev软件包里面有json-c的头文件以及开发需要的库文件。头文件放在了/usr/include/json/json.h目录下,写代码的时候要注意!或者安装下面这个包也行:
apt-get install libjson-c-dev
json-c类型
typedef enum json_type {
/* If you change this, be sure to update json_type_to_name() too */
json_type_null,
json_type_boolean,
json_type_double,
json_type_int,
json_type_object,
json_type_array,
json_type_string,
} json_type;
来自头文件,写代码的时候有时候需要判断json类型,根据json类型来解析。
json-c部分接口
1、将符合json格式的字符串构造为一个json对象
struct json_object *json_tokener_parse(const char *s);
2、将json对象内容,转成json格式的字符串
const char *json_object_to_json_string(struct json_object *obj);
3、创建json对象
struct json_object *json_object_new_object();
4、往json对象中添加键值对
void json_object_object_add(struct json_object *obj, const char *key, struct json_object *value);
5、将C字符串转换为JSON字符串格式的对象
struct json_object* json_object_new_string(const char *s);
6、将整数转换为JSON格式的对象
struct json_object* json_object_new_int(int32_t i);
7、获取json对象的整形数值(和5相反的操作)
int32_t json_object_get_int(struct json_object *obj);
8、获取json对象的字符串值(和6相反的操作)
const char *json_object_get_string(struct json_object *obj);
解析json分为两步:
第一步:根据键名,从json对象中获取对应数据的json对象
第二步:根据数据类型,将数据对应的json对象转化为对应类型的数据
9、根据键名获取对应的json对象
json_bool json_object_object_get_ex(struct json_object* obj, const char *key, struct json_object **value);
参数:obj 源json对象 key 键名 value 用于存放获取的对应数据的json对象,注意这里一定传入的是二级指针。不用传入实体
10、获取json对象的类型 类型有
json_type json_object_get_type(struct json_object *obj);
数组类型相关操作(json_type_array类型)
11、创建一个JSON数组类型JSON对象
struct json_object* json_object_new_array(void);
12、往json_type_array类型的json对象中添加一个元素
int json_object_array_add(struct json_object *obj, struct json_object *val);
13、获取json_type_array类型的json对象中指定下标的元素
struct json_object* json_object_array_get_idx(struct json_object *obj, int idx);
json对象和json格式字符串的转换
#include <stdio.h>
#include <json-c/json.h>

本文详细介绍了在嵌入式端侧使用JSON-C进行数据解析的方法,包括安装配置、常见API介绍及示例代码,展示了如何通过JSON-C与服务器进行通信,并提供了socket传输JSON数据的具体实现。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



