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

前端 未结 3 1247
有刺的猬
有刺的猬 2021-02-12 15:24

I am currently using Qt5.0 with the core QJson library to handle some data for the program I am developing.

To set the scene for this question I will provide you with so

相关标签:
3条回答
  • 2021-02-12 15:57

    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.

    0 讨论(0)
  • 2021-02-12 16:07

    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.

    0 讨论(0)
  • 2021-02-12 16:19

    I have had a similar problem for a couple of days and I have managed to find a workaround which works for me and I thought I should share it here.

    You can navigate to the object whose key-value you wish to update. Then use the "remove" method to delete the key-value pair and then use the "insert" method to insert it again with the new value.

    This might ruin the order of key-value pairs in your object but since you will anyways access by a key, it should not be a problem.

    The in-place changing of values is not supported as I found out the hard way :)

    0 讨论(0)
提交回复
热议问题