user1190832
user1190832

Reputation:

Qt - Writing integer data into JSON

I am using Qt (5.5) and I want to exchange data in JSON format in a client-server application.

So the format is constant:

{
    "ball":
    {
        "posx": 12,
        "posy": 35
    }
}

I would like to be able to define a ByteArray or string like so:

QByteArray data = "{\"ball\":{\"posx\":%s,\"posy\":%s}}"

and then just write whatever the values for that into the string.

How do I do that?

Upvotes: 0

Views: 2505

Answers (2)

phyatt
phyatt

Reputation: 19112

And here are more examples of string manipulations, but for readability and maintainability, please use the QJson classes.

QString str;
str = QString("{\"ball\":{\"posx\":%1,\"posy\":%2}}").arg(12).arg(35);
qDebug() << qPrintable(str);

QByteArray ba = str.toLocal8Bit();

qDebug() << ba;

QString str2;

str2 = "{\"ball\":{\"posx\":"
        + QString::number(12)
        + ",\"posy\":"
        + QString::number(35)
        + "}}";
qDebug() << qPrintable(str2);

output

{"ball":{"posx":12,"posy":35}}
"{"ball":{"posx":12,"posy":35}}"
{"ball":{"posx":12,"posy":35}}

Note again that the quotes are added by qDebug() when printing a QByteArray object.

Hope that helps.

Upvotes: 1

phyatt
phyatt

Reputation: 19112

QtJson is baked into Qt 5. It is easy to use, and gets it all ready for you pretty easily.

#include <QCoreApplication>
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>

void saveToJson(QJsonObject & json);

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QJsonObject jsonObject;

    saveToJson(jsonObject);

    QJsonDocument jsonDoc(jsonObject);

    qDebug() << "Example of QJsonDocument::toJson() >>>";
    qDebug() << jsonDoc.toJson();
    qDebug() << "<<<";

    return a.exec();
}

void saveToJson(QJsonObject & json)
{
    QJsonObject ball;
    ball["posx"] = 12;
    ball["posy"] = 35;

    json["ball"] = ball;
}

output

Example of QJsonDocument::toJson() >>>
"{
    "ball": {
        "posx": 12,
        "posy": 35
    }
}
"
<<<

Note: qDebug() wraps QString objects in quotes when printing. To get rid of that, pass your QString into qPrintable(). And it puts endl in for you at the end of each line.

For a more complex example see the official:

JSON Save Game Example

http://doc.qt.io/qt-5/qtcore-json-savegame-example.html

Hope that helps.

Upvotes: 3

Related Questions