How to serialize a QJSonObject?

banzsolt picture banzsolt · Jan 25, 2014 · Viewed 10.5k times · Source

I am new to the JSON and I started experimenting with it, but I couldn't manage to save any of my QJsonObject, or QJsonArrays at all. Did I get it right, if I want to get the Json format of my QjsonObject I have to serialize it?

Basically I want to save in a json file all my QJsonObsject but it's not working, here is my code

    QtJson::JsonObject ingredient;
    ingredient["name"] = newIngredient->GetName();
    ingredient["pirce"] = newIngredient->GetPrice();
    ingredient["date"] = newIngredient->GetDate();
    QByteArray data = Json::serialize(ingredient);

    qDebug() >> data;

Like I found out there is no more Json, not QJson, so is there any serialize() function what I could use? Thanks and sorry if I used the wrong terms, I am learning them yet.

Answer

user798377 picture user798377 · Mar 25, 2014

Use QJsonDocument to serialize/deserialize JSON. See below:

QJsonObject ingredient;
ingredient["name"] = QString("testName");
ingredient["date"] = QString("testDate");

QJsonDocument doc(ingredient);
QByteArray bytes = doc.toJson();

qDebug() << bytes;

This snippet will produce the following JSON output:

{
"date": "testDate",
"name": "testName"
}