I am using JSON in Qt for quite a time now and I always did it the way it is shown in the example. However, I would like to know if there is actually a difference between this direct assignment to the QJsonValueRef compared to using QJsonObject::insert
when adding items to QJsonObject, i.e. are these lines:
json["name"] = mName;
json.insert("name", mName);
different by any means or it is just a matter of a coding style?
Conceptually, it is different. The operator[](const QString &key)
returns a reference to the JSON value
(i.e. key
is not included) pointed by the key
, while insert
method will add/replace the value then return an iterator
to the value (i.e. we can access the key
and value
through the iterator). Thus, using operator[]
you only gained an access (reference) to a specific value pointed by key
, and when using insert
, you got an iterator
which can be used to access the element (key,value) itself and previous/next (if any) element in the JSON object.
Technically, according to the source code, in the operator[](const QString &key)
, first it will search a value pointed by key
and if exists, the reference will be returned. If the value does not exists insert
will be called with an empty QJSonValue() as the second argument, then a reference to this new value will be returned. Since your call to the operator[]
is followed by value modification, the effect of both operations in question will be the same, i.e. it assign mValue
to the element having key "name"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With