ArduinoJson助手
【推荐】直接根据输入数据、平台生成相应的代码
注意不同版本,函数声明、调用方式不一样
https://arduinojson.org/v7/assistant/#/step1
反序列化deserialization
#include <ArduinoJson.h>void setup() {// Initialize serial portSerial.begin(9600);while (!Serial)continue;// Allocate the JSON documentJsonDocument doc;// JSON input string.const char* json = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";// Deserialize the JSON documentDeserializationError error = deserializeJson(doc, json);// Test if parsing succeeds.if (error) {Serial.print(F("deserializeJson() failed: "));Serial.println(error.f_str());return;}// Fetch values.//// Most of the time, you can rely on the implicit casts.// In other case, you can do doc["time"].as<long>();const char* sensor = doc["sensor"];long time = doc["time"];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);
}void loop() {// not used in this example
}
序列化serialization
JsonDocument doc;
char Serial[];doc["sensor"] = "gps";
doc["time"] = 1351824120;
doc["data"][0] = 48.756080;
doc["data"][1] = 2.302038;serializeJson(doc, Serial);
Serial.println(Serial);
// This prints:
// {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}----------------#include <ArduinoJson.h>void setup() {// Initialize Serial portSerial.begin(9600);while (!Serial)continue;// Allocate the JSON documentJsonDocument doc;// Add values in the documentdoc["sensor"] = "gps";doc["time"] = 1351824120;// Add an array.JsonArray data = doc["data"].to<JsonArray>();data.add(48.756080);data.add(2.302038);//或//doc["data"][0] = 48.756080;//doc["data"][1] = 2.302038;// Generate the minified JSON and send it to the Serial port.serializeJson(doc, Serial);// The above line prints:// {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}// Start a new lineSerial.println();// Generate the prettified JSON and send it to the Serial port.serializeJsonPretty(doc, Serial);// The above line prints:// {// "sensor": "gps",// "time": 1351824120,// "data": [// 48.756080,// 2.302038// ]// }
}void loop() {// not used in this example
}