什么是JSON?
JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。采用完全獨立於編程語言的文本格式來存儲和表示數據。其簡潔和層次結構清晰的特點使得 JSON 易於人閱讀和編寫,同時也易於機器解析和生成,並有效地提升網絡傳輸效率。
JSON建構於兩種結構:
“名稱/值”對的集合(A collection of name/value pairs)。即常說的Key/Value 鍵/值對。不同的語言中,它被理解為對象(object),紀錄(record),結構(struct),字典(dictionary),哈希表(hash table),有鍵列表(keyed list),或者關聯數組 (associative array)。
值的有序列表(An ordered list of values)。在大部分語言中,它被理解為數組(array)。
eps8266的經典案例:
這里給出一個能在esp8266上能夠解析的最簡單的例子:
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
void printJson(cJSON * root)//以遞歸的方式打印json的最內層鍵值對
{
for(int i=0; i<cJSON_GetArraySize(root); i++) //遍歷最外層json鍵值對
{
cJSON * item = cJSON_GetArrayItem(root, i);
if(cJSON_Object == item->type) //如果對應鍵的值仍為cJSON_Object就遞歸調用printJson
printJson(item);
else //值不為json對象就直接打印出鍵和值
{
printf("%s->", item->string);
//printf("%s\n", cJSON_Print(item));//內存泄漏
}
}
}
int main()
{
char * jsonStr = "{\"semantic\":{\"slots\":{\"name\":\"Charlin\"}}, \"rc\":0, \"operation\":\"CALL\", \"service\":\"telephone\", \"text\":\"打電話給Charlin\"}";
cJSON * root = NULL;
cJSON * item = NULL;//cjson對象
root = cJSON_Parse(jsonStr);
if (!root)
{
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
}
else
{
printf("%s\n", "有格式的方式打印Json:");
printf("%s\n\n", cJSON_Print(root));//內存泄漏
printf("%s\n", "無格式方式打印json:");
printf("%s\n\n", cJSON_PrintUnformatted(root));//內存泄漏
printf("%s\n", "一步一步的獲取name 鍵值對:");
printf("%s\n", "獲取semantic下的cjson對象:");
item = cJSON_GetObjectItem(root, "semantic");//
printf("%s\n", cJSON_Print(item));//內存泄漏
printf("%s\n", "獲取slots下的cjson對象");
item = cJSON_GetObjectItem(item, "slots");
printf("%s\n", cJSON_Print(item));//內存泄漏
printf("%s\n", "獲取name下的cjson對象");
item = cJSON_GetObjectItem(item, "name");
printf("%s\n", cJSON_Print(item));//內存泄漏
printf("%s:", item->string); //看一下cjson對象的結構體中這兩個成員的意思
printf("%s\n", item->valuestring);
printf("\n%s\n", "打印json所有最內層鍵值對:");
printJson(root);
}
if(root)
cJSON_Delete(root); // 釋放內存
return 0;
}
這里只給出一個最簡單的例子:
詳情咨詢:(https://zhuanlan.zhihu.com/p/53730181)
順便做個廣告,本團隊承接ESP8266的方案業務,有需求的朋友歡飲咨詢。