mqtt协议(cJSON格式举例)
下面是一个使用 cJSON 库构建 JSON 数据的示例,展示如何创建各种 JSON 结构(对象、数组、嵌套结构),并将其转换为字符串:
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h" // 假设已包含cJSON头文件int main() {// 创建根JSON对象cJSON *root = cJSON_CreateObject();// 添加基本类型字段cJSON_AddNumberToObject(root, "id", 12345);cJSON_AddStringToObject(root, "name", "John Doe");cJSON_AddBoolToObject(root, "isStudent", 1); // 1表示true// 创建并添加数组cJSON *hobbies = cJSON_CreateArray();cJSON_AddItemToObject(root, "hobbies", hobbies);cJSON_AddItemToArray(hobbies, cJSON_CreateString("Reading"));cJSON_AddItemToArray(hobbies, cJSON_CreateString("Swimming"));cJSON_AddItemToArray(hobbies, cJSON_CreateString("Programming"));// 创建并添加嵌套对象cJSON *contact = cJSON_CreateObject();cJSON_AddItemToObject(root, "contact", contact);cJSON_AddStringToObject(contact, "email", "john@example.com");cJSON_AddStringToObject(contact, "phone", "+1-123-456-7890");// 创建并添加包含对象的数组cJSON *friends = cJSON_CreateArray();cJSON_AddItemToObject(root, "friends", friends);// 向friends数组添加对象cJSON *friend1 = cJSON_CreateObject();cJSON_AddStringToObject(friend1, "name", "Alice");cJSON_AddNumberToObject(friend1, "age", 25);cJSON_AddItemToArray(friends, friend1);cJSON *friend2 = cJSON_CreateObject();cJSON_AddStringToObject(friend2, "name", "Bob");cJSON_AddNumberToObject(friend2, "age", 28);cJSON_AddItemToArray(friends, friend2);// 将JSON结构转换为字符串char *jsonString = cJSON_Print(root);if (jsonString) {printf("生成的JSON字符串:\n%s\n", jsonString);free(jsonString); // 释放内存}// 释放cJSON对象cJSON_Delete(root);return 0;
}
生成的 JSON 格式示例:
{ "id": 12345, "name": "John Doe", "isStudent": true, "hobbies": ["Reading", "Swimming", "Programming"], "contact": { "email": "john@example.com", "phone": "+1-123-456-7890" }, "friends": [ { "name": "Alice", "age": 25 }, { "name": "Bob", "age": 28 } ] }
关键 API 说明:
-
创建 JSON 结构:
cJSON_CreateObject()
:创建 JSON 对象(花括号{}
)cJSON_CreateArray()
:创建 JSON 数组(方括号[]
)cJSON_CreateNumber()
:创建数值类型cJSON_CreateString()
:创建字符串类型cJSON_CreateBool()
:创建布尔类型
-
添加数据到对象:
cJSON_AddItemToObject()
:添加任意类型的项到对象cJSON_AddNumberToObject()
:添加数值项(简化版)cJSON_AddStringToObject()
:添加字符串项(简化版)
-
添加数据到数组:
cJSON_AddItemToArray()
:添加项到数组
-
转换与释放:
cJSON_Print()
:将 JSON 结构转换为格式化字符串cJSON_PrintUnformatted()
:转换为无格式字符串(节省空间)cJSON_Delete()
:释放 JSON 对象占用的内存