Picture of Sascha
Registered 5 years 141 days
Sascha Tuesday, 7 March 2023, 07:46 AM
Question about the behaviour of the json_io class
Hello everyone,

I have come across a behaviour which I did not expect.

Here a little bit of sampel code:

char jsonStringBuffer[256];
json_io jsonData(jsonStringBuffer);
word jsonBase = jsonData.add_object(JSON_ID_ROOT, 0);

// add string to the root object of the json
jsonData.add_string(jsonBase, "mt", "testevent");

// add a new object to the root object of the json
word objectBase = jsonData.add_object(jsonBase, "newObject") :
jsonData.add_string(objectBase, "data", "testData");

// add something in the root object again
jsonData.add_string(jsonBase, "test", "123456");

// this line will not work
jsonData.add_string(objectBase, "data2", "testData123123");


Why will the line with the comment "this line will not work" not be added to the json? I would have expected that this will work. But like I said this line will not add anything to the json. It even works fine without any error messages that there was done something wrong.

Regards,
Sascha
Andreas Fink
Moderator Registered 12 years 277 days
Andreas Fink (innovaphone) Tuesday, 7 March 2023, 01:00 PM
Re: Question about the behaviour of the json_io class
Hello Sascha,

indeed, the order is important, when entries are added to the object structure.

It is not possible to jump back in the hierarchy of the JSON to add something.

In this example, adding val1 and vl2 must happen after "obj" is created and before any additions on the level of "obj" are happened:
{
"mt": "Request",
"obj": {
"val1": "a",
"val2": "b"
},
"src": "src0"
}

Workarounds are:
- keep the order straight, according to the object hierarchy
- use additional json_io instance to store "obj" structure, and add it later to the main json_io instance

Best Regards
Andreas Fink
Picture of Sascha
Registered 5 years 141 days
Sascha Tuesday, 7 March 2023, 01:43 PM
Re: Question about the behaviour of the json_io class
Hello Andreas,

thank you for these informations.

Regards,
Sascha
← You can define your color theme preference here