I have a JSON string
{
"FirstName": "John",
"LastName": "Doe",
"Age": 43,
"Address": {
"Street": "Downing Street 10",
"City": "London",
"Country": "Great Britain"
},
"Phone numbers": [
"+44 1234567",
"+44 2345678"
]
}
in QString variable. I found (somewhere here in Stackoverflow) a way to format XML:
QString responseData = "";
responseData = networkResponse->readAll();
QString formattedXMLResponse;
QDomDocument input;
input.setContent(responseData);
QDomDocument output(input);
QTextStream stream(&formattedXMLResponse);
output.save(stream, 2);
ui->outputTB->setPlainText(formattedXMLResponse);
But this code works fine just for XML. Any thoughts how JSON can be formatted?
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).
Qt provides support for dealing with JSON data. JSON is a format to encode object data derived from Javascript, but now widely used as a data exchange format on the internet. The JSON support in Qt provides an easy to use C++ API to parse, modify and save JSON data.
QJsonDocument takes a format to its toJson function, allowing you to specify either a compact or indented format.
Assuming you have your JSON in a QJsonObject called jsonObj:-
QJsonDocument doc(jsonObj);
QString jsonString = doc.toJson(QJsonDocument::Indented);
Or, from a QString:-
QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
QString formattedJsonString = doc.toJson(QJsonDocument::Indented);
If you use Qt 4, you can use QJson lib.
In this case the usage will be as following:
QJson::Parser parser;
bool ok;
QVariantMap result = parser.parse (responseData, &ok).toMap();
if (!ok) {
qFatal("An error occurred during parsing");
exit (1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With