首先看一下这两个接口的定义:
-
QJsonArray Class
The QJsonArray class encapsulates a JSON array. More...
Header: | #include <QJsonArray> |
qmake: | QT += core |
Since: | Qt 5.0 |
- insert方法的官方定义:
void QJsonArray::insert(int i, const QJsonValue &value)
Inserts value at index position i in the array. If i is 0, the value is prepended to the array. If i is size(), the value is appended to the array.
See also append(), prepend(), replace(), and removeAt().
iterator QJsonArray::insert(iterator before, const QJsonValue &value)
Inserts value before the position pointed to by before, and returns an iterator pointing to the newly inserted item.
-
QJsonObject Class
The QJsonObject class encapsulates a JSON object. More...
Header: | #include <QJsonObject> |
qmake: | QT += core |
Since: | Qt 5.0 |
- insert方法的官方定义:
iterator QJsonObject::insert(const QString &key, const QJsonValue &value)
Inserts a new item with the key key and a value of value.
If there is already an item with the key key, then that item's value is replaced with value.
Returns an iterator pointing to the inserted item.
If the value is QJsonValue::Undefined, it will cause the key to get removed from the object. The returned iterator will then point to end().
See also remove(), take(), QJsonObject::iterator, and end().
两个接口的对象中各自insert插入方法的区别:
在jsonObject中插入键值对的顺序和文件中的键值对顺序不太一样(顺序相反),这是因为JSON中的object本身是指无序的键值对,它不能确保我们插入的顺序和实际保存的数据顺序一致。如果你的数据需要顺序一致,考虑JSON中的array,array是值的有序列表。
插入值的代码:
// 构建 JSON 对象
QJsonObject json;
json.insert("Name", "Qt");
json.insert("From", 1991);
json.insert("Cross Platform", true);
结果:(顺序相反)
{
"Cross Platform": true,
"From": 1991,
"Name": "Qt"
}
解决办法:可以逆序调用insert方法插入值;或者用QJsonArray接口。
而在jsonArray中插入值的顺序与文件中的顺序是一致的,本身就是数组,自带下标(索引)。
插入值的代码:
// 构建 Json 数组 - Version
QJsonArray versionArray;
versionArray.append(4.8);
versionArray.append(5.2);
versionArray.append(5.7);
结果:(顺序一致)
"Version": [
4.8,
5.2,
5.7
]
参考学习: