ArduinoJson
ArduinoJson(全稱:ArduinoJson-C++ JSON Library for IoT) 是嵌入式系統中優雅和高效的Json庫。它僅使用最基本的API,確保工作時消耗最小的內存空間。雖然它的命名中包含“Arduino”,但事實上並沒有引用Arduino的任何庫文件。ArduinoJson基於MIT開源協議,也就是說它是免費的,因此可以應用在任何的C++項目中。
序列化是將對象狀態轉換爲可保持或可傳輸的格式的過程。與序列化相對的是反序列化,它將流轉換爲對象。這兩個過程結合起來,可以輕鬆地存儲和傳輸數據。序列化與反序列化,在Esp8266中使用就是在連接到服務器之後,收發數據的處理。
官方實例代碼
前提是需要在Arduino編譯器裏面下載安裝ArduinoJson庫文件。
#include <ArduinoJson.h>
void setup() {
Serial.begin(9600);
DynamicJsonDocument doc(1024);
// WARNING: the string in the input will be duplicated in the JsonDocument.
String input = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
deserializeJson(doc, input);
JsonObject obj = doc.as<JsonObject>();
// You can use a String to get an element of a JsonObject
// No duplication is done.
//反序列化
long time = obj[String("time")];
String sensor = obj["sensor"];
double latitude = doc["data"][0];
double longitude = doc["data"][1];
// Print values.
Serial.println(sensor);
Serial.println(time);
Serial.println(latitude, 6);
Serial.println(longitude, 6);
//序列化
obj["sensor"] = "new gps";
obj["code"] = 200;
// Lastly, you can print the resulting JSON to a String
String output;
serializeJson(doc, output);
Serial.println(output);
}
void loop() {
// not used in this example
}
結果:
deserializeJson(doc, input),反序列化,將object 對象轉換成 string。 serializeJson(doc, output),內容序列化爲json格式字符串,以便於傳輸。
DynamicJsonDocument doc(1024);
JsonObject obj = doc.as();
創建了一個動態json,設置屬性。
實例ESP8266使用ArduinoJson
自己使用Esp8266處理服務器收到數據代碼,可以看我下一篇博客,關於Esp8266連接阿里雲服務器。
官方地址
更多ArduinoJson庫的相關資料請在官網查看。https://arduinojson.org/
ArduinoJson Assistant可以幫助自動計算Size大小。