[209] | 1 | // Copyright Benoit Blanchon 2014-2016
|
---|
| 2 | // MIT License
|
---|
| 3 | //
|
---|
| 4 | // Arduino JSON library
|
---|
| 5 | // https://github.com/bblanchon/ArduinoJson
|
---|
| 6 | // If you like this project, please add a star!
|
---|
| 7 |
|
---|
| 8 | #include <ArduinoJson.h>
|
---|
| 9 |
|
---|
| 10 | void setup() {
|
---|
| 11 | Serial.begin(9600);
|
---|
| 12 | while (!Serial) {
|
---|
| 13 | // wait serial port initialization
|
---|
| 14 | }
|
---|
| 15 |
|
---|
| 16 | // Memory pool for JSON object tree.
|
---|
| 17 | //
|
---|
| 18 | // Inside the brackets, 200 is the size of the pool in bytes,
|
---|
| 19 | // If the JSON object is more complex, you need to increase that value.
|
---|
| 20 | StaticJsonBuffer<200> jsonBuffer;
|
---|
| 21 |
|
---|
| 22 | // StaticJsonBuffer allocates memory on the stack, it can be
|
---|
| 23 | // replaced by DynamicJsonBuffer which allocates in the heap.
|
---|
| 24 | // It's simpler but less efficient.
|
---|
| 25 | //
|
---|
| 26 | // DynamicJsonBuffer jsonBuffer;
|
---|
| 27 |
|
---|
| 28 | // JSON input string.
|
---|
| 29 | //
|
---|
| 30 | // It's better to use a char[] as shown here.
|
---|
| 31 | // If you use a const char* or a String, ArduinoJson will
|
---|
| 32 | // have to make a copy of the input in the JsonBuffer.
|
---|
| 33 | char json[] =
|
---|
| 34 | "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
|
---|
| 35 |
|
---|
| 36 | // Root of the object tree.
|
---|
| 37 | //
|
---|
| 38 | // It's a reference to the JsonObject, the actual bytes are inside the
|
---|
| 39 | // JsonBuffer with all the other nodes of the object tree.
|
---|
| 40 | // Memory is freed when jsonBuffer goes out of scope.
|
---|
| 41 | JsonObject& root = jsonBuffer.parseObject(json);
|
---|
| 42 |
|
---|
| 43 | // Test if parsing succeeds.
|
---|
| 44 | if (!root.success()) {
|
---|
| 45 | Serial.println("parseObject() failed");
|
---|
| 46 | return;
|
---|
| 47 | }
|
---|
| 48 |
|
---|
| 49 | // Fetch values.
|
---|
| 50 | //
|
---|
| 51 | // Most of the time, you can rely on the implicit casts.
|
---|
| 52 | // In other case, you can do root["time"].as<long>();
|
---|
| 53 | const char* sensor = root["sensor"];
|
---|
| 54 | long time = root["time"];
|
---|
| 55 | double latitude = root["data"][0];
|
---|
| 56 | double longitude = root["data"][1];
|
---|
| 57 |
|
---|
| 58 | // Print values.
|
---|
| 59 | Serial.println(sensor);
|
---|
| 60 | Serial.println(time);
|
---|
| 61 | Serial.println(latitude, 6);
|
---|
| 62 | Serial.println(longitude, 6);
|
---|
| 63 | }
|
---|
| 64 |
|
---|
| 65 | void loop() {
|
---|
| 66 | // not used in this example
|
---|
| 67 | }
|
---|