Empaquetado json de comunicación de red

Prefacio:

Por qué se necesita el empaquetado json:

        Para evitar los problemas de alineación de bytes e inconsistencia en el tamaño de tipo en diferentes plataformas, la biblioteca json encapsula los datos en datos de flujo de caracteres con un determinado formato para la transmisión.

formato json:

        Correspondencia uno a uno entre datos y valores clave. Ambas partes de la transmisión de datos acuerdan el mismo valor clave y utilizan la interfaz API para operar el objeto Jason (jason_object) para almacenar u obtener datos según el valor clave.

Uso general:

        Datos --->objeto json (encapsulado) --->formato de cadena---------> ---->transmisión---->---->formato de cadena---->( Análisis) Objeto Jason ----> Obtener datos (int, char...) y almacenarlos en un objeto json en pares con valor clave ----> Obtener datos del objeto json a través del valor clave 

API de interfaz json: (nota: todos los tipos de datos (arry, int, string, char) en json son un objeto jason)

1. Encapsulación de datos (objeto único (int, char, cadena) y matriz (arry))

        (1) Nuevo objeto:

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) Conversión de objetos json (tipos comunes -> objetos 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) Procesamiento de objetos 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 Al flujo de caracteres:

const char * json_object_to_json_string (struct json_object *obj)

2. Análisis de datos: desembalaje

        (1) Flujo de caracteres a json_object

struct json_object*	json_tokener_parse(const char *str)

        (2) Adquisición de objetos

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) Conversión de objetos (restauración de datos)

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)

3. Prueba

(1) Primero defina la estructura que necesita empaquetarse. Puede definirla usted mismo. La estructura se utiliza aquí para facilitar varios tipos de transmisión de datos. Las personas pueden empaquetar datos según sus propias necesidades.

//通信结构体
typedef struct user
{
	int work;   //工作指令
	int flag;   //反馈信息
	char username[30];  //登录昵称
	char passwd[30];  //登录密码
	char othername[30];  //私聊对象
	char msg[300];   //消息内容
	int online;     //在线状态

}data_t;

(2) Función de embalaje:

//打包数据-
const char * pack_user(data_t user){
	//创建大对象
    struct json_object* objects= json_object_new_object();
    //2>将数据打包成json小对象(约定的结构体中有几个成员就打包几个小对象)
    struct json_object* values1=json_object_new_int(user.work);
    struct json_object* values2=json_object_new_int(user.flag);
    struct json_object* values3=json_object_new_string(user.username);
    struct json_object* values4=json_object_new_string(user.passwd);
	struct json_object* values5=json_object_new_string(user.othername);
	struct json_object* values6=json_object_new_string(user.msg);
	struct json_object* values7=json_object_new_int(user.online);
    //3>贴标签放入大对象
    json_object_object_add (objects,"work",values1);
    json_object_object_add (objects,"flag",values2);
	json_object_object_add (objects,"username",values3);
    json_object_object_add (objects,"passwd",values4);
	json_object_object_add (objects,"othername",values5);
	json_object_object_add (objects,"msg",values6);
	json_object_object_add (objects,"online",values7);
    //4>大对象转成字符串类型
    const char *p=json_object_to_json_string(objects);
//	printf("test 263\n");
    char* str = malloc(500);  // 动态分配内存
    strcpy(str,p);
    return str;
}

(3) Función de descomprimir datos:

data_t  unpack_user( const char *js){
    static data_t rslt;
    //解析json,还原数据成原来的类型
    struct json_object * sale_json=json_tokener_parse(js);

    //根据标签key获取小对象数据
    struct json_object * sale_obj1=json_object_object_get(sale_json,"work");
    struct json_object * sale_obj2=json_object_object_get(sale_json,"flag");
    struct json_object * sale_obj3=json_object_object_get(sale_json,"username");
    struct json_object * sale_obj4=json_object_object_get(sale_json,"passwd");
    struct json_object * sale_obj5=json_object_object_get(sale_json,"othername");
    struct json_object * sale_obj6=json_object_object_get(sale_json,"msg");
    struct json_object * sale_obj7=json_object_object_get(sale_json,"online");


    //提取小对象里面的数据
    rslt.work=json_object_get_int (sale_obj1);
    rslt.flag=json_object_get_int (sale_obj2);
    strcpy(rslt.username,json_object_get_string (sale_obj3));
    //strcpy(rslt.username,wd1);
    strcpy(rslt.passwd,json_object_get_string (sale_obj4));
    //strcpy(rslt.passwd,wd2);
    strcpy(rslt.othername,json_object_get_string (sale_obj5));
    //strcpy(rslt.othername,wd3);
    strcpy(rslt.msg,json_object_get_string (sale_obj6));
    //strcpy(rslt.msg,wd4);
    rslt.online=json_object_get_int (sale_obj7);

    return rslt;
}

(4)Uso:

char buf[100];
//接受打包传来的数据,放在buf里面
bzero(buf,strlen(buf));//清空buf里面的垃圾值,再接受
int ret = recv(cid,buf,sizeof(char)*1000,0);//接收数据
//将打包的数据赋值给data_t类型
data_t request = unpack_user(buf);
//将结构体打包成char*类型,通过strcpy函数赋值给p
char *p;
strcpy(p,pack_user(request)));

 

Supongo que te gusta

Origin blog.csdn.net/apple_71040140/article/details/132667802
Recomendado
Clasificación