linux下使用JSON传输数据

一.在Linux下安装json库

       想要在Linux上方便的使用json,需要在linux上安装json库

       1)首先先下载json库压缩包,照着链接里的说明安装即可。

               链接:https://pan.baidu.com/s/1QsXeBa9cWtYthxkfPZKvkw 
              提取码:bkop 

二.安装步骤:

    1.拷贝并解压到ubuntu系统 json-c-0.9.tar.gz
        命令: tar xvf json-c-0.9.tar.gz
    2.执行安装命令
        命令:  ./configure
            make
            sudo make install

三.json函数介绍

json: 为了避免不同平台下的字节对齐、类型大小不统一的问题,json库把数据封装成具有一定格式的字符流数据,进行传输。

json格式:把数据与键值一一对应,数据传输双方约定好同一键值,

使用接口API根据键值操作jason对象(jason_object)存储或取得数据。

一般使用:

数据-》(封装)jason对象-》String格式-》。。。传输。。。-》String格式-》(解析)jason对象-》取得数据

(int、char..)数据,与键值成对存入json对象—————————————————————————————————>通过键值从json对象取得数据

json接口API(注意:在json中所有数据类型(arry、int、string、char)都是一个jason对象)

1、数据的封装(单对象(int、char、string)和数组(arry))

(1)新建对象:

A.创建一个Json对象:

struct json_object * json_object_new_object (void)

B.创建一个Json数组对象:

struct json_object * json_object_new_array (void)

C.销毁json对象

void json_object_put (struct json_object *obj)

(2)json对象的转换(普通类型->json对象):

1:struct json_object * json_object_new_int (int i)

2:struct json_object * json_object_new_double (double d)

3:struct json_object * json_object_new_string (const char *s)

4:struct json_object * json_object_new_boolean (boolean b)

5:struct json_object * json_object_new_string_len (const char *s, int len)

(3)json对象的处理

A.普通对象

添加:void json_object_object_add (struct json_object *obj, const char *key, struct json_object *val)

删除:void json_object_object_del (struct json_object *obj, const char *key)

查询:struct json_object * json_object_object_get (struct json_object *obj, const char *key)

根据key获取:struct json_object * json_object_object_get (struct json_object *obj, const char *key)

B.数组对象

获取长度:int json_object_array_length (struct json_object *obj)

添加:int json_object_array_add (struct json_object *obj, struct json_object *val)

指定位置添加:int json_object_array_put_idx (struct json_object *obj, int idx, struct json_object *val)

获取指定位置对象:struct json_object * json_object_array_get_idx (struct json_object *obj, int idx)

(4)json_object To 字符流

const char * json_object_to_json_string (struct json_object *obj)

 

1、数据的解析(解析获取到的json格式字符流)

(1)字符流 To json_object

struct json_object* json_tokener_parse(const char *str)

(2)对象获取

A.普通对象

根据key获取:struct json_object * json_object_object_get (struct json_object *obj, const char *key)

B.数组对象

获取指定位置对象:struct json_object * json_object_array_get_idx (struct json_object *obj, int idx)

(3)对象的转换(数据还原)

bool型:boolean json_object_get_boolean (struct json_object *obj)

double型:double json_object_get_double (struct json_object *obj)

整型:int json_object_get_int (struct json_object *obj)

字符数组:const char * json_object_get_string (struct json_object *obj)

 

四、接下条通过简单例子介绍下

1.json函数封装

#include "myhead.h"


//传cmd和结构体进去返回一个json打包好的buf
char *pack_json(char *cmd,data mydata) 
{

	char *data_buf = (char *)malloc(512);

	//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 *value0=json_object_new_string(cmd);

	struct json_object *value1=json_object_new_string(mydata.username);
	struct json_object *value2=json_object_new_string(mydata.userpasswd);
	struct json_object *value3=json_object_new_string(mydata.devid);
	struct json_object *value4=json_object_new_string(mydata.superpasswd);
	struct json_object *value5=json_object_new_string(mydata.time_passwd);
	struct json_object *value6=json_object_new_string(mydata.fingerid);
	struct json_object *value7=json_object_new_int(mydata.flag);
	struct json_object *value8=json_object_new_string(mydata.phone);
	struct json_object *value9=json_object_new_string(mydata.dev_name);

	//4、把数值对象添加到字符串对象中
	json_object_object_add(str1,"cmd", value0);

	json_object_object_add(str2,"username", value1);
	json_object_object_add(str2,"userpasswd", value2);
	json_object_object_add(str2,"devid", value3);
	json_object_object_add(str2,"superpasswd", value4);
	json_object_object_add(str2,"time_passwd", value5);
	json_object_object_add(str2,"fingerid", value6);
	json_object_object_add(str2,"flag", value7);
	json_object_object_add(str2,"phone", value8);
	json_object_object_add(str2,"dev_name", value9);


	//5、把字符串对象添加到数组对象中
	json_object_array_add(arr,str1);
	json_object_array_add(arr,str2);

	//6、把数组对象转为字符流进行发送
	const char *temp=json_object_to_json_string(arr);
	bzero(data_buf,sizeof(data_buf));
	strcpy(data_buf,temp);
	printf("%s\n",temp);

	return data_buf;

}

//将收到的buf解包成cmd
char *get_cmd(char *buf)
{	
	char *cmd_buf=(char *)malloc(10);
	//1、把得到的字符流转为数组对象
	struct json_object *arr=json_tokener_parse(buf);

	//2、获取数组指定位置的对象
	struct json_object *str1=json_object_array_get_idx(arr,0);

	//3、在字符串{}对象中根据key值找到数值对象
	struct json_object *value1=json_object_object_get(str1,"cmd");

	//4、数值对象转换为对应的数值
	const char *temp = json_object_get_string(value1);

	//bzero(cam_buf,sizeof(cmd_buf));
	strcpy(cmd_buf,temp);

	return cmd_buf;
}


//将收到的jsonbuf返回一个结构体
data *get_struct(char *buf)
{
	data *mydata = (data *)malloc(sizeof(data));
	//1、把得到的字符流转为数组对象
	struct json_object *arr=json_tokener_parse(buf);

	//2、获取数组指定位置的对象
	struct json_object *str1=json_object_array_get_idx(arr,1);

	//3、在字符串{}对象中根据key值找到数值对象
	struct json_object *value1=json_object_object_get(str1,"username");
	struct json_object *value2=json_object_object_get(str1,"userpasswd");
	struct json_object *value3=json_object_object_get(str1,"devid");
	struct json_object *value4=json_object_object_get(str1,"superpasswd");
	struct json_object *value5=json_object_object_get(str1,"time_passwd");
	struct json_object *value6=json_object_object_get(str1,"fingerid");
	struct json_object *value7=json_object_object_get(str1,"flag");
	struct json_object *value8=json_object_object_get(str1,"phone");
	struct json_object *value9=json_object_object_get(str1,"dev_name");

	//4、数值对象转换为对应的数值
	const char *temp1 = json_object_get_string(value1);
	const char *temp2 = json_object_get_string(value2);
	const char *temp3 = json_object_get_string(value3);
	const char *temp4 = json_object_get_string(value4);
	const char *temp5 = json_object_get_string(value5);
	const char *temp6 = json_object_get_string(value6);
	const int temp7 = json_object_get_int(value7);
	const char *temp8 = json_object_get_string(value8);
	const char *temp9 = json_object_get_string(value9);

	strcpy(mydata->username,temp1);
	strcpy(mydata->userpasswd,temp2);
	strcpy(mydata->devid,temp3);
	strcpy(mydata->superpasswd,temp4);
	strcpy(mydata->time_passwd,temp5);
	strcpy(mydata->fingerid,temp6);
	mydata->flag = temp7;
	strcpy(mydata->phone,temp8);
	strcpy(mydata->dev_name,temp9);

	return mydata;
}

2.客户端编写

#include "myhead.h"

#define PORT 31415
#define IP_ADDR  "192.168.5.188"

int main(int argc, char const *argv[])
{
	int fd = socket(AF_INET,SOCK_STREAM,0);
	char cmd[10] = "d100";
	char buf[512];
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port =htons(PORT);
    server.sin_addr.s_addr = inet_addr(IP_ADDR);
    int ret = connect(fd,(struct sockaddr *)(&server),sizeof(server));
    if(ret < 0){
    	printf("connect error!!!\n");
    	perror("connect");
    	return 0;
    }else{
	printf("success!\n");
    }

    data mydata = {
    	.username = "hhhhhhh",
    	.userpasswd = "pppppp",
    	.devid = "ppqpqpq",
    	.superpasswd = "oooo",
    	.time_passwd = "1234",
    	.fingerid = "iooo",
    	.flag = 1,
    	.phone = "1008610000",
    	.dev_name = "haib",
    };

    bzero(buf,sizeof(buf));
    strcpy(buf,pack_json(cmd,mydata));
    printf("buf=%s\n",buf );

    send(fd,buf,strlen(buf),0);

	return 0;
}

3.服务器端编写

#include "myhead.h"

#define PORT 31415
#define IP_ADDR  "192.168.5.188"


int main(int argc, char const *argv[])
{
	int fd = socket(AF_INET,SOCK_STREAM,0);
	int on=1;
	char buf[512];
	char cmd[10];

	setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));

	struct sockaddr_in server; //定义一个结构体用来描述服务器
	server.sin_family=AF_INET;
	server.sin_port = htons(PORT);
	server.sin_addr.s_addr = inet_addr(IP_ADDR);
	int ret = bind(fd,(struct sockaddr *)(&server),sizeof(server));
	if(ret == -1){
		printf("绑定服务器失败!\n");
		perror("bind");
		exit(1);
	}else
		printf("绑定服务器成功!\n");

	listen(fd,10);
	struct sockaddr_in client;
	int length = sizeof(client);
	int newfd = accept(fd,(struct sockaddr *)(&client),&length);
	printf("客户端%d已连接,IP:%s   主机号:%d\n",newfd,inet_ntoa(client.sin_addr),ntohs(client.sin_port));

	recv(newfd,buf,sizeof(buf),0);
	printf("buf=%s\n", buf);

	bzero(cmd,sizeof(cmd));
	strcpy(cmd,get_cmd(buf));
	printf("cmd=%s\n",cmd);

	data *test = get_struct(buf);

	printf("suername = %s\n",test->username);
	printf("superpasswd = %s\n",test->userpasswd);
	printf("devid=%s\n",test->devid);



	return 0;
}

4.头文件(有些多余的头文件~懒得删了)

#ifndef _MYHEAD_H
#define _MYHEAD_H

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <pthread.h>
#include "/usr/local/include/json/json.h"


typedef struct Data{
	char username[20];      //用户名
	char userpasswd[20];    //用户密码
	char devid[20];         // 设备ID-->设备一联网就发送设备ID和超级密码
	char superpasswd[20];   //设备超级密码
	char time_passwd[20];	//设备开锁临时密码
	char fingerid[20];		//指纹ID编号
	int  flag;				//返回值,返回0表示操作失败,返回1表示操作成功
	char phone[20];			//应急电话号码
	char dev_name[20];		//用户自定义的设备名,与设备ID对应
}data;

extern char *pack_json(char *cmd,data mydata);
extern char *get_cmd(char *buf);
extern data *get_struct(char *buf);

#endif

5.用GCC编译

gcc server.c  json_fun.c -o server -ljson

gcc client.c  json_fun.c -o client -ljson

运行结果

绑定服务器成功!
客户端4已连接,IP:192.168.5.188   主机号:50306
buf=[ { "cmd": "d100" }, { "username": "hhhhhhh", "userpasswd": "pppppp", "devid": "ppqpqpq", "superpasswd": "oooo", "time_passwd": "1234", "fingerid": "iooo", "flag": 1, "phone": "1008610000", "dev_name": "haib" } ]
cmd=d100
suername = hhhhhhh
superpasswd = pppppp
devid=ppqpqpq
--------------------------------------------------------------------------------------------------

success!
[ { "cmd": "d100" }, { "username": "hhhhhhh", "userpasswd": "pppppp", "devid": "ppqpqpq", "superpasswd": "oooo", "time_passwd": "1234", "fingerid": "iooo", "flag": 1, "phone": "1008610000", "dev_name": "haib" } ]
buf=[ { "cmd": "d100" }, { "username": "hhhhhhh", "userpasswd": "pppppp", "devid": "ppqpqpq", "superpasswd": "oooo", "time_passwd": "1234", "fingerid": "iooo", "flag": 1, "phone": "1008610000", "dev_name": "haib" } ]
 

运行的时候遇到一个问题,就是会报找不到动态库libjson.so.0,解决方法是:

  1. # vim /etc/ld.so.conf //在新的一行中加入库文件所在目录

  2. /usr/lib

  3.  
  4. # ldconfig //更新/etc/ld.so.cache文件

 

 

 

 

 

 

 

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值