How to instantiate Array of Structs

Hi,

I have the following Json data which contains an array of objects/structs:


 { "interaction":2,
    "devices": [
      {
        "id": "7",
        "brightness": 100,
        "hue": 10000,
        "saturation": 254,
        "power":true
      },
      {
        "id": "8",
        "brightness": 100,
        "hue": 10000,
        "saturation": 254,
        "power":true
      },
      {
        "id": "9",
        "brightness": 100,
        "hue": 10000,
        "saturation": 254,
        "power":true
      }
    ]
}

Using @rickkas7 JsonParserGeneratorRK library I want to parse the Json to obtain the devices array and then iterate over the array items. Seems like something simple, but I can’t determine how to instantiate the array correctly to assign it a value.

 void runInteraction(String commands){
   jsonParser.clear();
   jsonParser.addString(commands);
 
  deviceArray[] = {}; //how do I instantiate this
  jsonParser.getOuterValueByKey("devices", deviceArray);

  for( unsigned int i = 0; i < sizeof(deviceArray)/sizeof(deviceArray[0]); i++ ){
    Serial.println(deviceArray[i].power);
  }
 }

C++ is a new language for me, so still wrapping my head around the data types and their differences compared to other languages. Thanks.

Take a look at vectors. They let you dynamically create arrays:

http://www.cplusplus.com/reference/vector/vector/

you’ll have to parse each JSON value and then you can store it in the vector using push_back to add an element.

Vector is a great idea but maybe you do not need dynamic allocation?

#define NUMDEVICES 10
struct devices{
     uint8_t id;
     uint8_t brightness;
     uint16_t hue;
     uint8_t saturation;
     bool power;
};
devices device[NUMDEVICES];      //to create an array of structs called device

You can then access the devices and struct with . notation.

devices[1].brightness

2 Likes