How to change QJsonObject value in a QJson hierarchy without using copies?

陌路散爱 提交于 2019-12-04 23:02:26

According to information from Qt developer who actually wrote QJson in Qt5 -

What's currently included in Qt is a 'read-only' implementation to provide parsing facilities. He has an intention to extend design with 'references' support in future, but it's not yet done.

After wasting three hours of my life I can confirm that as of today this is still impossible with Qt 5.4. You can modify JSON objects, but not nested JSON objects.

The problem is that the code such as:

json["aa"].toObject()["bb"] = 123;

essentially means the following:

QJsonObject temp = json["aa"].toObject();
temp["bb"] = 123;

and since temp is not a reference but object (and toObject() doesn't return a reference), the assignment is compiled but then discarded.

Essentially it breaks down to the fact that it is impossible to obtain the reference to an object you just created, meaning you cannot create them from left to right, i.e. aa["bb"] -> aa["bb"]["cc"] etc - you cannot obtain reference to aa["bb"], only a copy of its value.

What IS possible though is to recreate the JSON with a new value added, as described here: https://forum.qt.io/topic/25096/modify-nested-qjsonvalue/4 - note that this keeps recreating the object each time it is called, and is essentially memory usage disaster, but this is all Qt currently allows.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!