JSON与结构体互转
JSON与结构体互转(jsonutil.h/.c)
以cJSON为例,封装结构体与JSON互转,便于配置、协议等场景。
// jsonutil.h
#ifndef JSONUTIL_H
#define JSONUTIL_H
#include <cJSON.h>
typedefstruct {
int id;
char name;
} user_t;
cJSON *user_to_json(const user_t *user);
intjson_to_user(const cJSON *json, user_t *user);
#endif
// jsonutil.c
#include "jsonutil.h"
cJSON *user_to_json(const user_t *user) {
cJSON *obj = cJSON_CreateObject();
cJSON_AddNumberToObject(obj, "id", user->id);
cJSON_AddStringToObject(obj, "name", user->name);
return obj;
}
intjson_to_user(const cJSON *json, user_t *user) {
if (!cJSON_IsObject(json)) return-1;
user->id = cJSON_GetObjectItem(json, "id")->valueint;
strncpy(user->name, cJSON_GetObjectItem(json, "name")->valuestring, sizeof(user->name));
return0;
} JSON与结构体互转可以直接使用的 JSON与结构体互转 JSON与结构体互转很实用的 很实用的案例 JSON与结构体互转很不错的结构体 JSON与结构体互转 封装结构体与JSON互转,便于配置、协议等场景
页:
[1]