Skip to content
domonetic edited this page Nov 5, 2015 · 8 revisions

Example 1: complex nested object

From issue #85:

[
  {
    "error": {
      "address": "",
      "description": "link button not pressed",
      "type": "101"
    }
  }
]

Can be generated with the following code:

DynamicJsonBuffer jsonBuffer;
JsonArray& root = jsonBuffer.createArray();
JsonObject& error = root.createNestedObject().createNestedObject("error");
error["address"] = "";
error["description"] = "link button not pressed";
error["type"] = "101";
root.prettyPrintTo(Serial);

And, while stored in char json[] can be decoded with the following code:

DynamicJsonBuffer jsonBuffer;
JsonArray& root = jsonBuffer.parseArray(json);
JsonObject& error = root[0]["error"];
const char* address = error["address"];
const char* description = error["description"];
int type = error["type"];

Don't forget to replace the DynamicJsonBuffer by a StaticJsonBuffer if you need to run on an embedded platform like an Arduino.

Example 2: get the weather data from aviationweather.gov or geonames.org

char *MTserverName = "api.geonames.org";        // server name
String cmd = "GET /weatherIcaoJSON?ICAO=";      // prepare the command to send to the web server after 

getting the data on JSON format and parsing the buffer:

  JsonObject& _root = jsonBuffer.parseObject(MTjson);  // parse the JSON buffer

  if (!_root.success()) {                            // everything OK
      Serial.println("MTparseObject() failed");
      delay(10000);
      __wferrno=-2;                                   // set the error code 
      return NULL;
      }
  if (Debug&&Debugplus) Serial.println("Beauty print...");
  if (Debug&&Debugplus) _root.prettyPrintTo(Serial);  // print it on prettyPrint format
  if (Debug&&Debugplus) Serial.println("END of Beauty print...");
  
  JsonObject & _ooo     = _root["weatherObservation"];  // query root
  MET->MTobservation    = _ooo ["observation"];  // raw observation  
  MET->MTtemp           = _ooo ["temperature"];  // temp
  MET->MTpressure       = _ooo ["hectoPascAltimeter"];  // QNH
  MET->MTQNH            = _ooo ["hectoPascAltimeter"];  // QNH
  MET->MTdewpoint       = _ooo ["dewPoint"];  // Dew point
  MET->MThumidity       = _ooo ["humidity"];  // humidity %
  MET->MTwinddeg        = _ooo ["windDirection"];  // wind
  MET->MTwindspeed      = _ooo ["windSpeed"];  // speed
  MET->MTobservationtime= _ooo ["datetime"];  // time

Example 3: iterators

char json[] = "[\"A\",\"B\",\"C\"]";
JsonArray& array = jsonBuffer.parseArray(json);

for(JsonArray::iterator it=array.begin(); it!=array.end(); ++it) 
{
    // *it contains the JsonVariant which can be casted as usuals
    const char* value = *it;

    // this also works: 
    value = it->as<const char*>();    

}
char json[] = "{\"key\":\"value\"}";
JsonObject& object = jsonBuffer.parseObject(json);

for(JsonObject::iterator it=object.begin(); it!=object.end(); ++it) 
{
    // *it contains the key/value pair
    const char* key = it->key;

    // it->value contains the JsonVariant which can be casted as usual
    const char* value = it->value;

    // this also works
    value = it->value.as<const char*>();
    
}

Example 4: Serialize and Deserialize

Here is the canonical example for serializing and deserializing with ArduinoJson. By following this example, you are making the best usage of your memory and you maintain a good software design.

struct SensorData {
   const char* name;
   int time;
   float value;
};

#define SENSORDATA_JSON_SIZE (JSON_OBJECT_SIZE(3))

bool deserialize(SensorData& data, char* json)
{
    StaticJsonBuffer<SENSORDATA_JSON_SIZE> jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(json);
    data.name = root["name"];
    data.time = root["time"];
    data.value = root["value"];
    return root.success();
}

void serialize(const SensorData& data, char* json, size_t maxSize)
{
    StaticJsonBuffer<SENSORDATA_JSON_SIZE> jsonBuffer;
    JsonObject& root = jsonBuffer.createObject();
    root["name"] = data.name;
    root["time"] = data.time;
    root["value"] = data.value;
    root.printTo(json, maxSize);
}

Clone this wiki locally