QT QJsonObject 与 QJsonArray 中insert()方法 插入值的顺序问题

首先看一下这两个接口的定义:

  • 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.

See also erase() and insert().

  • 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
    ]

 参考学习:

https://blog.csdn.net/m0_37194132/article/details/85085584

https://yq.aliyun.com/articles/119861

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值