Skip to content
GitLab
Projects Groups Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in / Register
  • A ArduinoJson
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
  • Issues 24
    • Issues 24
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 0
    • Merge requests 0
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Deployments
    • Deployments
    • Environments
    • Releases
  • Packages and registries
    • Packages and registries
    • Package Registry
    • Infrastructure Registry
  • Monitor
    • Monitor
    • Incidents
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • Benoît Blanchon
  • ArduinoJson
  • Issues
  • #1023
Closed
Open
Issue created Jun 12, 2019 by Administrator@rootContributor

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;
}
Assignee
Assign to
Time tracking