c语言结构体转为json字符串 使用jansson库
时间: 2024-02-23 07:01:49 浏览: 145
要使用jansson库将C语言结构体转为JSON字符串,可以按照以下步骤进行:
1. 定义C语言结构体,例如:
```c
typedef struct {
int id;
char name[20];
double score;
} Student;
```
2. 使用jansson库中的json_object()函数创建一个JSON对象,并使用json_object_set()函数将结构体中的成员变量添加到JSON对象中,例如:
```c
json_t *json = json_object();
json_object_set(json, "id", json_integer(student.id));
json_object_set(json, "name", json_string(student.name));
json_object_set(json, "score", json_real(student.score));
```
3. 使用json_dumps()函数将JSON对象转为JSON字符串,例如:
```c
char *json_str = json_dumps(json, JSON_COMPACT);
```
完整代码示例:
```c
#include <stdio.h>
#include <string.h>
#include <jansson.h>
typedef struct {
int id;
char name[20];
double score;
} Student;
int main() {
// 初始化结构体
Student student = {1, "Tom", 89.5};
// 创建JSON对象
json_t *json = json_object();
json_object_set(json, "id", json_integer(student.id));
json_object_set(json, "name", json_string(student.name));
json_object_set(json, "score", json_real(student.score));
// 转为JSON字符串
char *json_str = json_dumps(json, JSON_COMPACT);
// 输出JSON字符串
printf("%s\n", json_str);
// 释放内存
free(json_str);
json_decref(json);
return 0;
}
```
输出结果为:
```json
{"id":1,"name":"Tom","score":89.5}
```
阅读全文
相关推荐


















