使用ArduinoJson庫解析json數(shù)據(jù)忧吟,基于Version 6
-
第一步:申請內(nèi)存哥攘,這個一定要根據(jù)自己的需求去申請內(nèi)存大小虱颗。
// Allocate the JSON document // // Inside the brackets, 200 is the capacity of the memory pool in bytes. // Don't forget to change this value to match your JSON document. // Use arduinojson.org/v6/assistant to compute the capacity. StaticJsonDocument<200> doc;
-
包裝數(shù)據(jù)
// JSON input string. // // It's better to use a char[] as shown here. // If you use a const char* or a String, ArduinoJson will // have to make a copy of the input in the JsonBuffer. char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; // Root of the object tree. // // It's a reference to the JsonObject, the actual bytes are inside the // JsonBuffer with all the other nodes of the object tree. // Memory is freed when jsonBuffer goes out of scope. JsonObject& root = jsonBuffer.parseObject(json);
-
驗證
// Deserialize the JSON document DeserializationError error = deserializeJson(doc, json); // Test if parsing succeeds. if (error) { Serial.print(F("deserializeJson() failed: ")); Serial.println(error.f_str()); return; }
-
Json數(shù)據(jù)的解析
// 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); }
包裝Json數(shù)據(jù)