用C语言系列化出以下JSON{"stm32":[{"name":"temp","val":30.3},{"name":"humi","val":41},{"name":"bat","val":92.6},{"name":"led","val":"0"}]}
时间: 2023-07-06 14:37:41 浏览: 46
以下是使用C语言将给定数据序列化为JSON格式的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <json-c/json.h>
int main() {
// 定义数据
float temp = 30.3;
int humi = 41;
float bat = 92.6;
bool led = false;
// 创建 JSON 对象
struct json_object *stm32 = json_object_new_array();
struct json_object *temp_obj = json_object_new_object();
struct json_object *humi_obj = json_object_new_object();
struct json_object *bat_obj = json_object_new_object();
struct json_object *led_obj = json_object_new_object();
// 添加数据到 JSON 对象中
json_object_object_add(temp_obj, "name", json_object_new_string("temp"));
json_object_object_add(temp_obj, "val", json_object_new_double(temp));
json_object_array_add(stm32, temp_obj);
json_object_object_add(humi_obj, "name", json_object_new_string("humi"));
json_object_object_add(humi_obj, "val", json_object_new_int(humi));
json_object_array_add(stm32, humi_obj);
json_object_object_add(bat_obj, "name", json_object_new_string("bat"));
json_object_object_add(bat_obj, "val", json_object_new_double(bat));
json_object_array_add(stm32, bat_obj);
json_object_object_add(led_obj, "name", json_object_new_string("led"));
json_object_object_add(led_obj, "val", json_object_new_boolean(led));
json_object_array_add(stm32, led_obj);
// 序列化 JSON 对象
const char *json_string = json_object_to_json_string(stm32);
// 输出序列化后的 JSON 字符串
printf("%s\n", json_string);
// 释放 JSON 对象的内存
json_object_put(stm32);
json_object_put(temp_obj);
json_object_put(humi_obj);
json_object_put(bat_obj);
json_object_put(led_obj);
return 0;
}
```
上述代码将输出以下JSON字符串:
```
[{"name":"temp","val":30.299999237060547},{"name":"humi","val":41},{"name":"bat","val":92.599998474121094},{"name":"led","val":false}]
```
可以看到,输出的JSON字符串与要求的格式一致。