| 1 | // ArduinoJson - https://arduinojson.org |
| 2 | // Copyright © 2014-2026, Benoit BLANCHON |
| 3 | // MIT License |
| 4 | // |
| 5 | // This example shows how to deserialize a JSON document with ArduinoJson. |
| 6 | // |
| 7 | // https://arduinojson.org/v7/example/parser/ |
| 8 | |
| 9 | #include <ArduinoJson.h> |
| 10 | |
| 11 | void setup() { |
| 12 | // Initialize serial port |
| 13 | Serial.begin(9600); |
| 14 | while (!Serial) |
| 15 | continue; |
| 16 | |
| 17 | // Allocate the JSON document |
| 18 | JsonDocument doc; |
| 19 | |
| 20 | // JSON input string. |
| 21 | const char* json = |
| 22 | "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; |
| 23 | |
| 24 | // Deserialize the JSON document |
| 25 | DeserializationError error = deserializeJson(doc, json); |
| 26 | |
| 27 | // Test if parsing succeeds |
| 28 | if (error) { |
| 29 | Serial.print(F("deserializeJson() failed: ")); |
| 30 | Serial.println(error.f_str()); |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | // Fetch the values |
| 35 | // |
| 36 | // Most of the time, you can rely on the implicit casts. |
| 37 | // In other case, you can do doc["time"].as<long>(); |
| 38 | const char* sensor = doc["sensor"]; |
| 39 | long time = doc["time"]; |
| 40 | double latitude = doc["data"][0]; |
| 41 | double longitude = doc["data"][1]; |
| 42 | |
| 43 | // Print the values |
| 44 | Serial.println(sensor); |
| 45 | Serial.println(time); |
| 46 | Serial.println(latitude, 6); |
| 47 | Serial.println(longitude, 6); |
| 48 | } |
| 49 | |
| 50 | void loop() { |
| 51 | // not used in this example |
| 52 | } |
| 53 | |
| 54 | // See also |
| 55 | // -------- |
| 56 | // |
| 57 | // https://arduinojson.org/ contains the documentation for all the functions |
| 58 | // used above. It also includes an FAQ that will help you solve any |
| 59 | // deserialization problem. |
| 60 | // |
| 61 | // The book "Mastering ArduinoJson" contains a tutorial on deserialization. |
| 62 | // It begins with a simple example, like the one above, and then adds more |
| 63 | // features like deserializing directly from a file or an HTTP request. |
| 64 | // Learn more at https://arduinojson.org/book/ |
| 65 | // Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤ |