Create Json using QJsonDocument
Solved
General and Desktop
-
How can I create a Json like this
{ "FirstName": "John", "LastName": "Doe", "Age": 43, "Address": { "Street": "Downing Street 10", "City": "London", "Country": "Great Britain" }, "Phone numbers": [ "+44 1234567", "+44 2345678" ] }
I created a sample code but I struck in the middle
QJsonDocument json; QJsonArray recordsArray; QJsonObject recordObject; recordObject.insert("FirstName", QJsonValue::fromVariant("John")); recordObject.insert("LastName", QJsonValue::fromVariant("Doe")); recordObject.insert("Age", QJsonValue::fromVariant(43)); // ???? recordsArray.push_back(recordObject); json.setArray(recordsArray);
-
One way to create the JSON document you presented:
QJsonObject recordObject; recordObject.insert("FirstName", QJsonValue::fromVariant("John")); recordObject.insert("LastName", QJsonValue::fromVariant("Doe")); recordObject.insert("Age", QJsonValue::fromVariant(43)); QJsonObject addressObject; addressObject.insert("Street", "Downing Street 10"); addressObject.insert("City", "London"); addressObject.insert("Country", "Great Britain"); recordObject.insert("Address", addressObject); QJsonArray phoneNumbersArray; phoneNumbersArray.push_back("+44 1234567"); phoneNumbersArray.push_back("+44 2345678"); recordObject.insert("Phone Numbers", phoneNumbersArray); QJsonDocument doc(recordObject); qDebug() << doc.toJson();
Output:
{ "Address": { "City": "London", "Country": "Great Britain", "Street": "Downing Street 10" }, "Age": 43, "FirstName": "John", "LastName": "Doe", "Phone Numbers": [ "+44 1234567", "+44 2345678" ] }
recordsArray.push_back(recordObject);
json.setArray(recordsArray);This suggests you might be trying to make the top-level document an array, in which case:
QJsonObject recordObject; recordObject.insert("FirstName", QJsonValue::fromVariant("John")); recordObject.insert("LastName", QJsonValue::fromVariant("Doe")); recordObject.insert("Age", QJsonValue::fromVariant(43)); QJsonObject addressObject; addressObject.insert("Street", "Downing Street 10"); addressObject.insert("City", "London"); addressObject.insert("Country", "Great Britain"); recordObject.insert("Address", addressObject); QJsonArray phoneNumbersArray; phoneNumbersArray.push_back("+44 1234567"); phoneNumbersArray.push_back("+44 2345678"); recordObject.insert("Phone Numbers", phoneNumbersArray); QJsonArray recordsArray; recordsArray.push_back(recordObject); QJsonDocument doc(recordsArray); qDebug() << doc.toJson();
Output:
[ { "Address": { "City": "London", "Country": "Great Britain", "Street": "Downing Street 10" }, "Age": 43, "FirstName": "John", "LastName": "Doe", "Phone Numbers": [ "+44 1234567", "+44 2345678" ] } ]
I hope that helps :)
-
@Paul-Colby Thank you