Is there a simpler way of building and modifying a QJsonObject?
-
For example, I would like to build the following json (its a simple one for the sake of the sample, in real life I have to construct much larger objects):
{ "person":{ "salary": { "min": 10000, "max": 20000 } } }
I build this object something like this (there might be syntax errors, I did not check):
QJsonObject({{"person", QJsonObject({{"salary", QJsonObject({{"min", 10000}, {"max", 20000}})}})}})
It can get quite ugly. Is there a better way of constructing such JsonOBject? The min/max values I obtain them dynamically at run time, so they cannot be imported with QJsonDocument::fromJson just like that.
-
For example, I would like to build the following json (its a simple one for the sake of the sample, in real life I have to construct much larger objects):
{ "person":{ "salary": { "min": 10000, "max": 20000 } } }
I build this object something like this (there might be syntax errors, I did not check):
QJsonObject({{"person", QJsonObject({{"salary", QJsonObject({{"min", 10000}, {"max", 20000}})}})}})
It can get quite ugly. Is there a better way of constructing such JsonOBject? The min/max values I obtain them dynamically at run time, so they cannot be imported with QJsonDocument::fromJson just like that.
@need4openid Depending on your exact use case you can read JSON from a string.
-
Hi,
Depending on what you would like to do you might also want to consider nlohmann's json library which is quite good.
-
Hi
if you are using a c++ 11 compiler you can also use raw string literals.QString jsontemplate = R"( { "person":{ "salary": { "min": %1, "max": %2 } } })"; QString finaleJson = jsontemplate.arg(1000).arg(2000); qDebug() << finaleJson;
ps. +5 for nlohmann's json. Its awesome.
-
@need4openid said in Is there a simpler way of building and modifying a QJsonObject?:
QJsonObject({{"person", QJsonObject({{"salary", QJsonObject({{"min", 10000}, {"max", 20000}})}})}})
QJsonValue Foo::getValues() const { return {{"person", m_person}, {"salary", m_salary}, {"min", m_min}, {"max", m_max}, }
-
-
If it is more convenient for you to manage the data in a collection (map or hash table), there are methods to create QJsonObject from QVariantMap and QVaraintHash.
int min = 10000, max = 20000; QVariantMap salary; salary["max"] = max; salary["min"] = min; QVariantMap person; person["salary"] = salary; QVariantMap jsonMap; jsonMap["person"] = person; QJsonDocument jsonDoc(QJsonObject::fromVariantMap(jsonMap)); qDebug() << jsonDoc.toJson(QJsonDocument::Compact);