[开发资料] JSON与结构体互转

[复制链接]
122|7
LOVEEVER 发表于 2025-8-19 12:00 | 显示全部楼层 |阅读模式

JSON与结构体互转(jsonutil.h/.c)
以cJSON为例,封装结构体与JSON互转,便于配置、协议等场景。

  1. // jsonutil.h
  2. #ifndef JSONUTIL_H
  3. #define JSONUTIL_H
  4. #include <cJSON.h>
  5. typedefstruct {
  6.     int id;
  7.     char name[32];
  8. } user_t;
  9. cJSON *user_to_json(const user_t *user);
  10. intjson_to_user(const cJSON *json, user_t *user);
  11. #endif

  1. // jsonutil.c
  2. #include "jsonutil.h"
  3. cJSON *user_to_json(const user_t *user) {
  4.     cJSON *obj = cJSON_CreateObject();
  5.     cJSON_AddNumberToObject(obj, "id", user->id);
  6.     cJSON_AddStringToObject(obj, "name", user->name);
  7.     return obj;
  8. }
  9. intjson_to_user(const cJSON *json, user_t *user) {
  10.     if (!cJSON_IsObject(json)) return-1;
  11.     user->id = cJSON_GetObjectItem(json, "id")->valueint;
  12.     strncpy(user->name, cJSON_GetObjectItem(json, "name")->valuestring, sizeof(user->name));
  13.     return0;
  14. }
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互转,便于配置、协议等场景
您需要登录后才可以回帖 登录 | 注册

本版积分规则

350

主题

2689

帖子

6

粉丝
快速回复 在线客服 返回列表 返回顶部