移植
1、json-c-master源码下载
百度云链接:链接:https://pan.baidu.com/s/1O5wBlQ8MgvNpfdSlsCMavw
提取码:lr01
2、安装工具
autoconf automake libtool 必须安装好
$ sudo apt-get install autoconf
$ sudo apt-get install automake
$ sudo apt-get install libtool
3、配置
$ ./autogen.sh
$ ./configure --host=arm-linux-gnueabihf --prefix=/usr/local
4、修改根目录 config.h
屏蔽下面四句话
/* Define to rpl_malloc if the replacement function should be used. /
//#define malloc rpl_malloc
/ Define to rpl_realloc if the replacement function should be used. */
//#define realloc rpl_realloc
5、编译 安装
make -j8
make install
6、将根目录 .libs的所以.so库全部拷贝到arm板子的 /usr/lib/下面,拷贝记得加-d软连接。
7、编译执行文件
添加 头文件 # include “json.h”
arm-linux-gnueabihf-gcc json_test.c -o json_test -std=c99 -I/usr/local/include/json-c/ -L /usr/local/lib/ -ljson-c
api使用
/从文件中获取json对象/
int id = -1; //用于保存账号的值
int pwd_len = 0;
char *pwd = NULL; //用于保存密码的值
char *cmd = NULL; //用于保存cmd的值
struct json_object * json_policy_array;
json_policy_array = json_object_from_file("./test.json");
printf("%s\n",json_object_to_json_string(json_policy_array));
/*从json对象中获取json对象*/
struct json_object * json_params ;
json_params = json_object_object_get(json_policy_array,"name");
printf("%s\n",json_object_to_json_string(json_params));
/*从json对象中获取数据,首先获取对象,然后进行类型转换,转成int、float、string等*/
id = json_object_get_int(json_object_object_get(json_policy_array,"alexa"));
printf("id = %d\n", id);
cmd = json_object_get_string(json_object_object_get(json_policy_array,"name"));
printf("cmd = %s\n", cmd);
pwd_len = json_object_get_string_len(json_object_object_get(json_policy_array,"site"));
pwd = json_object_get_string(json_object_object_get(json_policy_array,"site"));
printf("pwd_len = %d\n", pwd_len);
printf("pwd = %s\n", pwd);
/*向json文件中添加数据*/
//创建一个json对象newPobj
char *result = "OK";
//往json_policy_array里面添加键值对
json_object_object_add(json_policy_array,"id",json_object_new_int(200));
json_object_object_add(json_policy_array,"password",json_object_new_string("password2"));
//这时还是将配置信息存在内存中呢
printf("%s\n",json_object_to_json_string(json_policy_array));
//将内存中修改后的配置文件,写会到磁盘中
json_object_to_file("./test.json",json_policy_array);
//释放内存
//引用计数方式,无需手动释放