LOVEEVER 发表于 2025-8-19 12:00

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;
}

AdaMaYun 发表于 2025-9-18 09:54

JSON与结构体互转可以直接使用的

小小蚂蚁举千斤 发表于 2025-9-23 08:18

JSON与结构体互转

jf101 发表于 2025-9-23 16:44

JSON与结构体互转很实用的

中国龙芯CDX 发表于 2025-9-25 14:27

很实用的案例

OKAKAKO 发表于 2025-9-26 17:11

JSON与结构体互转很不错的结构体

星辰大海不退缩 发表于 2025-9-27 13:40

JSON与结构体互转

小夏天的大西瓜 发表于 2025-9-28 15:47

封装结构体与JSON互转,便于配置、协议等场景
页: [1]
查看完整版本: JSON与结构体互转