JSON与结构体互转(jsonutil.h/.c)
以cJSON为例,封装结构体与JSON互转,便于配置、协议等场景。
- // jsonutil.h
- #ifndef JSONUTIL_H
- #define JSONUTIL_H
- #include <cJSON.h>
- typedefstruct {
- int id;
- char name[32];
- } 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;
- }
|