COME FROM : usage-QJson
Usage
This page provides a quick overview of QJson’s features:
- parsing: from JSON to QVariant.
- serializing: from QVariant to JSON.
- QObject helper: dump and restore QObject’s attributes.
For more details checkout QJson’s documentation.
Parsing: from JSON to QVariant
Converting JSON’s data to QVariant instance is really simple:
// create a Parser instance
QJson::Parser parser;
bool ok;
// json is a QString containing the data to convert
QVariant result = parser.parse (json, &ok);
Suppose you’re going to convert this JSON data:
{
"encoding" : "UTF-8",
"plug-ins" : [
"python",
"c++",
"ruby"
],
"indent" : { "length" : 3, "use_space" : true }
}
The following code would convert the JSON data and parse it:
QJson::Parser parser;
bool ok;
QVariantMap result = parser.parse (json, &ok).toMap();
if (!ok) {
qFatal("An error occurred during parsing");
exit (1);
}
qDebug() << "encoding:" << result["encoding"].toString();
qDebug() << "plugins:";
foreach (QVariant plugin, result["plug-ins"].toList()) {
qDebug() << "\t-" << plugin.toString();
}
QVariantMap nestedMap = result["indent"].toMap();
qDebug() << "length:" << nestedMap["length"].toInt();
qDebug() << "use_space:" << nestedMap["use_space"].toBool();
The output would be:
encoding: "UTF-8"
plugins:
- "python"
- "c++"
- "ruby"
length: 3
use_space: true
Serialization: from QVariant to JSON
QVariant objects are converted to a string containing the JSON data.
Let’s declare a QVariant object with some data to convert:
QVariantList people;
QVariantMap bob;
bob.insert("Name", "Bob");
bob.insert("Phonenumber", 123);
QVariantMap alice;
alice.insert("Name", "Alice");
alice.insert("Phonenumber", 321);
people << bob << alice;
Now it’s time to create the Serializer
:
QJson::Serializer serializer;
bool ok;
QByteArray json = serializer.serialize(people, &ok);
if (ok) {
qDebug() << json;
} else {
qCritical() << "Something went wrong:" << serializer.errorMessage();
}
The output will be:
[
{
"Name" : "Bob", "Phonenumber" : 123
},
{
"Name" : "Alice", "Phonenumber" : 321
}
]
It’s possible to tune the indentation level of the resulting string using the Serializer::setIndentMode()
method