0
0
0142016-12-31 00:23:08
Qt
014, 2016-12-31 00:23:08

How to make it easier to access json nested object in Qt?

There is this json

{
   "firstName": "Иван",
   "lastName": "Иванов",
   "address": {
       "streetAddress": "Московское ш., 101, кв.101",
       "city": "Ленинград",
       "postalCode": 101101
   },
   "phoneNumbers": [
       "812 123-1234",
       "916 123-4567"
   ]
}

to change the value of the city key , you have to do the following construction:
QFile j_file( "file.json" );

   if( !j_file.open( QIODevice::ReadOnly | QIODevice::Text ) )
     qDebug() << "Err open file";

   QJsonDocument j_doc = QJsonDocument::fromJson( j_file.readAll() );

   QJsonObject j_obj = j_doc.object();
   QJsonValue j_val = "Piter";
   QJsonObject jo(j_obj["address"].toObject());
   jo["city"] = j_val;
   j_obj["address"] = jo;

In my opinion, it looks somehow clumsy, but if the investment is even deeper ... Tell me how to competently get access to the necessary keys.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
014, 2017-01-04
@014

I found a function that allows you to easily go to any depth and modify the values.

void parseJson::modifyJsonValue(QJsonObject &obj, const QString &path, const QJsonValue &newValue)
{
  const int indexOfDot = path.indexOf( '.' );
  qDebug() << indexOfDot;
  const QString propertyName = path.left( indexOfDot );
  qDebug() << propertyName;
  const QString subPath = indexOfDot > 0 ? path.mid(indexOfDot + 1) : QString();

  QJsonValue subValue = obj[ propertyName ];

  if(subPath.isEmpty()) {
  subValue = newValue;
  }
  else {
  QJsonObject obj = subValue.toObject();
  modifyJsonValue(obj,subPath,newValue);
  subValue = obj;
  }

  obj[propertyName] = subValue;
  }
  void modifyJsonValue(QJsonDocument& doc, const QString& path, const QJsonValue& newValue) {
  QJsonObject obj = doc.object();
  modifyJsonValue(obj,path,newValue);
  doc = QJsonDocument(obj);
}

R
Rou1997, 2016-12-31
@Rou1997

XPath.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question