目的:
java app Tcp客户端发送数据给Linux C 服务器数据解析
sudo cp tar xvf json-c-0.9.tar.gz /usr/local
cd /usr/local
sudo tar -xvf tar xvf json-c-0.9.tar.gz
cd xvf json-c-0.9.tar.gz
./configure
make
sudo make install
代码demo如下:
#include
#include "/usr/local/include/json/json.h"
/*
实现把点菜的信息以json打包与解析:
【{"name":"烤土豆",“price”:20},{"name":"小龙虾","price":300}】
*/
#include
#include "/usr/local/include/json/json.h"
int main(int argc, char const *argv[])
{
//1、创建一个json数组对象,就可以理解为外面那个大容器[]
struct json_object *arr=json_object_new_array();
//2、创建两个字符串对象,可以以理解为[]中的两个小容器{}
struct json_object *str1=json_object_new_object();
struct json_object *str2=json_object_new_object();
//3、把要存放的数据转为对象
struct json_object *value1=json_object_new_string("烤土豆");
struct json_object *value2=json_object_new_int(20);
struct json_object *value3=json_object_new_string("小龙虾");
struct json_object *value4=json_object_new_int(300);
//4、把数值对象添加到字符串对象中
json_object_object_add(str1,"name", value1);
json_object_object_add(str1,"price", value2);
json_object_object_add(str2,"name", value3);
json_object_object_add(str2,"price", value4);
//5、把字符串对象添加到数组对象中
json_object_array_add(arr,str1);
json_object_array_add(arr,str2);
//6、把数组对象转为字符流进行发送
const char *temp=json_object_to_json_string(arr);
printf("%s\n",temp);
//1、把得到的字符流转为数组对象
arr=json_tokener_parse(temp);
//2、获取数组指定位置的对象
str1=json_object_array_get_idx(arr,0);
str2=json_object_array_get_idx(arr,1);
//3、在字符串{}对象中根据key值找到数值对象
value1=json_object_object_get(str1,"name");
value2=json_object_object_get(str1,"price");
value3=json_object_object_get(str2,"name");
value4=json_object_object_get(str2,"price");
//4、数值对象转换为对应的数值
temp=json_object_get_string(value1);
int n=json_object_get_int(value2);
printf("%s : %d\n",temp,n);
temp=json_object_get_string(value3);
n=json_object_get_int(value4);
printf("%s : %d\n",temp,n);
return 0;
}