I have done it in two different ways,:
- using JsonObject as object for whole array and JsonArray for each array item;
- using JsonArray bor both, for whole array and for each item.
See code below, you can comment out defines on the beginning to control which way to use...
#include <ArduinoJson.h>
JsonDocument JSON_Obj;
struct MyStruct { int index; const char* EffectName; bool Selected; };
MyStruct MyArray[] =
{
{1, "First", false},
{5, "Second", true},
{3, "Third", false},
};
const size_t MyArrayCnt = sizeof MyArray / sizeof * MyArray;
#define ExtObject_IntArray
//#define ExtObject_IntObject
void setup()
{
Serial.begin(115200);
delay(1000); //for stability
Serial.println();Serial.println();
//Added plain variables
JSON_Obj["Var2"] = String("before array");
#ifdef ExtObject_IntArray
//External JsonObject, Internal JsonArray
JsonObject ExtObj1 = JSON_Obj["ArrayName1"].createNestedObject();
for (uint8_t i=0; i<MyArrayCnt; i++)
{
JsonArray IntArr1 = ExtObj1["ArrayIndex"+String(i)].to<JsonArray>();
IntArr1.add(MyArray[i].index);
IntArr1.add(MyArray[i].EffectName);
IntArr1.add(MyArray[i].Selected);
}
#endif
#ifdef ExtObject_IntObject
//External JsonObject, Internal JsonObject
JsonObject ExtObj2 = JSON_Obj["ArrayName2"].createNestedObject();
for (uint8_t i=0; i<MyArrayCnt; i++)
{
MyStruct s = MyArray[i];
JsonObject IntObj2 = ExtObj2["ArrayIndex"+String(i)].createNestedObject();
IntObj2["index"] = s.index;
IntObj2["EffectName"] = s.EffectName;
IntObj2["Selected"] =s.Selected;
}
#endif
//added more plain variablex
JSON_Obj["Var3"] = String("after array");
String jsonString;
//serializeJson(JSON_Obj, jsonString);
serializeJsonPretty(JSON_Obj, jsonString);
Serial.println(jsonString);
}
void loop()
{
}
First approach gives output like this:
{
"Var2": "before array",
"ArrayName1": [
{
"ArrayIndex0": [
1,
"First",
false
],
"ArrayIndex1": [
5,
"Second",
true
],
"ArrayIndex2": [
3,
"Third",
false
]
}
],
"Var3": "after array"
}
The output of the second one is here:
{
"Var2": "before array",
"ArrayName2": [
{
"ArrayIndex0": [
{
"index": 1,
"EffectName": "First",
"Selected": false
}
],
"ArrayIndex1": [
{
"index": 5,
"EffectName": "Second",
"Selected": true
}
],
"ArrayIndex2": [
{
"index": 3,
"EffectName": "Third",
"Selected": false
}
]
}
],
"Var3": "after array"
}
I like first one more, less text :-). Now, I need to decode it on the java-script side.
Thanks to all.