c++jsonqtqt5qjsonobject

remove curly brackets from qjsonarray and replace square brackets from document


I'm inserting lot of different values to QJsonObjects like this:

//gender inserted to QJsonObject gender
QJsonObject gender;
gender.insert("gender", person->gender());

//birthDate inserted to QJsonObject birthDate
QJsonObject birthDate;
birthDate.insert("birthDate", person->birthdate().toString());

After that I'm appending QJsonObjects to QJsonArray like this:

//Inserting all objects to QJsonDocument m_jsonDocument
QJsonArray allObjects;
allObjects.append(gender);
allObjects.append(birthDate);

Then im putting it all to QJsonDocument:

m_jsonDocument->setArray(allObjects);

Output:

[{
    "gender": "male"
},
{
    "birthDate": "2001-12-19"
}]

What I need is to remove curly brackets around objects and replace square brackets with curly brackets. Do I need to put these to QString and remove and replace or is there an easier way to modify either objects, arrays or whole document? I tried to look around but didn'n find the right solution yet.

This is how I would like to see the output:

{
"gender": "male",
"birthDate": "2001-12-19"}

There is a lot of stuff inside objects and it needs to be as a FHIR standard. There is objects inside objects and the document still needs lot of modifying.


Solution

  • You should only use a single QJsonObject and add the properties to that object:

    QJsonObject obj;
    obj.insert("gender",  person->gender());
    obj.insert("birthDate", person->birthdate().toString());
    m_jsonDocument->setObject(obj);
    

    Output:

    {
        "birthDate": "2001-12-19",
        "gender": "male"
    }