如何实现C语言中结构体与Json字符串之间的相互转换?
- 内容介绍
- 文章标签
- 相关推荐
本文共计874个文字,预计阅读时间需要4分钟。
在项目中,我们可能会遇到需要将一些预定义的本地结构体转换为Json字符串并发送到网络的情况。以下是一个简单的函数实现,该函数接收结构体指针,将其转换为Json字符串,并直接输出结果:
c#include #include
// 假设有一个简单的结构体typedef struct { int id; char name[50];} LocalStruct;
// 函数声明void structToJson(const LocalStruct *structPtr);
int main() { // 创建一个结构体实例 LocalStruct myStruct={1, Example Name};
// 调用函数 structToJson(&myStruct);
return 0;}
// 函数定义void structToJson(const LocalStruct *structPtr) { if (structPtr==NULL) return;
// 构建Json字符串 char jsonStr[1024]; snprintf(jsonStr, sizeof(jsonStr), {\id\:%d,\name\:\%s\}, structPtr->id, structPtr->name);
// 输出Json字符串 printf(%s\n, jsonStr);}
大家有没有在项目中遇到过,将一些预定义的本地结构体转换为Json字符串后,发送到网络中的情形。
本文共计874个文字,预计阅读时间需要4分钟。
在项目中,我们可能会遇到需要将一些预定义的本地结构体转换为Json字符串并发送到网络的情况。以下是一个简单的函数实现,该函数接收结构体指针,将其转换为Json字符串,并直接输出结果:
c#include #include
// 假设有一个简单的结构体typedef struct { int id; char name[50];} LocalStruct;
// 函数声明void structToJson(const LocalStruct *structPtr);
int main() { // 创建一个结构体实例 LocalStruct myStruct={1, Example Name};
// 调用函数 structToJson(&myStruct);
return 0;}
// 函数定义void structToJson(const LocalStruct *structPtr) { if (structPtr==NULL) return;
// 构建Json字符串 char jsonStr[1024]; snprintf(jsonStr, sizeof(jsonStr), {\id\:%d,\name\:\%s\}, structPtr->id, structPtr->name);
// 输出Json字符串 printf(%s\n, jsonStr);}
大家有没有在项目中遇到过,将一些预定义的本地结构体转换为Json字符串后,发送到网络中的情形。

