目的:
java app Tcp客户端发送数据给Linux C 服务器数据解析
验证环境:
首先安装json
安装包链接
链接:https://pan.baidu.com/s/1BDc2JldxTEmmcxwdqesvTw
提取码:54jg
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;
}
来个稍微负载的json对象包含json对象发送如下:
//创建一个json对象,理解为{},是一个容器
struct json_object * obj=json_object_new_object();
struct json_object * member=json_object_new_object();
//把要存放的数据转为对象
struct json_object *name_value=json_object_new_string(name);
struct json_object *passwd_value=json_object_new_string(passwd);
//把数值对象添加到字符串对象中
json_object_object_add(obj, USR_NAME, name_value);
json_object_object_add(obj, USR_PASSWD, passwd_value);
//member
struct json_object *mem_cmd=json_object_new_string("1");
struct json_object *mem_data=json_object_new_string("world");
json_object_object_add(member, "cmd", mem_cmd);
json_object_object_add(member, "data", mem_data);
//在json对象obj里添加“mem”成员member对象
json_object_object_add(obj, "mem", member);
//把Json对象转为字符流
const char *temp=json_object_to_json_string(obj);
printf("len:%d,dat:%s\n",strlen(temp),temp);
打印结果如下:
{ “usr_name”: “LBJ”, “usr_passwd”: “1”, “mem”: { “cmd”: “1”, “data”: “world” } }