How do I get a copy of a JsonDocument?
Created by: qwykx
Hello
I am currently migrating my application from ArduinoJson 5 to AruduinoJson 6 and I would like to work with JsonObjects in my functions.
In the following example the problem is that the JsonObject is a reference only and that means as soon as the the function returns, the JsonDocument is deallocated if I understood the documentation right.
So how can I use the JsonObject now without making the JsonDocument global?
// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2019
// MIT License
//
// This example shows how to deserialize a JSON document with ArduinoJson.
#include <iostream>
#include "ArduinoJson.h"
JsonObject getJson () {
DynamicJsonDocument doc(300);
// get the json via http here hard coded
char json[] =
"{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
// Deserialize the JSON document
deserializeJson(doc, json);
return doc.as<JsonObject>();
}
int main() {
JsonObject test = getJson();
// 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 = test["sensor"];
long time = test["time"];
double latitude = test["data"][0];
double longitude = test["data"][1];
int size = test["data"].size();
// Print values.
std::cout << sensor << std::endl;
std::cout << time << std::endl;
std::cout << latitude << std::endl;
std::cout << longitude << std::endl;
std::cout << size << std::endl;
return 0;
}