cJSON_Print
?和?cJSON_PrintUnformatted
?是 cJSON 庫中用于將 cJSON 對象轉換為 JSON 字符串的兩個函數,它們的區別主要在于輸出的格式:
1.?cJSON_Print
-
功能:將 cJSON 對象轉換為格式化的 JSON 字符串。
-
特點:
-
輸出的 JSON 字符串是格式化的(pretty-printed),包含換行符(
\n
)、縮進(空格或制表符)等,使其更易讀。 -
適合調試或需要人類可讀的場景。
-
-
示例輸出:
{"name": "Alice","age": 25,"city": "New York" }
2.?cJSON_PrintUnformatted
-
功能:將 cJSON 對象轉換為緊湊的、未格式化的 JSON 字符串。
-
特點:
-
輸出的 JSON 字符串是緊湊的,沒有多余的空白字符(如換行、縮進等)。
-
適合網絡傳輸或存儲,因為它的體積更小。
-
-
示例輸出:
{"name":"Alice","age":25,"city":"New York"}
主要區別總結
特性 | cJSON_Print | cJSON_PrintUnformatted |
---|---|---|
輸出格式 | 格式化(易讀) | 緊湊(無空格/換行) |
適用場景 | 調試、日志 | 網絡傳輸、存儲 |
字符串大小 | 較大(含格式字符) | 較小(無冗余字符) |
代碼示例
#include <stdio.h>
#include <cjson/cJSON.h>int main() {cJSON *root = cJSON_CreateObject();cJSON_AddStringToObject(root, "name", "Alice");cJSON_AddNumberToObject(root, "age", 25);cJSON_AddStringToObject(root, "city", "New York");// 格式化輸出char *formatted = cJSON_Print(root);printf("Formatted:\n%s\n", formatted);cJSON_free(formatted);// 未格式化輸出char *unformatted = cJSON_PrintUnformatted(root);printf("Unformatted:\n%s\n", unformatted);cJSON_free(unformatted);cJSON_Delete(root);return 0;
}
注意事項
-
兩者返回的字符串都需要手動釋放(通過?
cJSON_free
),避免內存泄漏。 -
如果 JSON 結構簡單,兩者的輸出差異可能不明顯,但對于復雜嵌套結構,格式化版本會更易讀