前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >QT QJsonObject 与 QJsonArray 中insert()方法 插入值的顺序问题

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

作者头像
acoolgiser
发布2019-08-29 10:36:42
8.7K1
发布2019-08-29 10:36:42
举报
文章被收录于专栏:acoolgiser_zhuanlan

版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。

本文链接:https://cloud.tencent.com/developer/article/1494968

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

  • 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是值的有序列表。

插入值的代码:

代码语言:javascript
复制
// 构建 JSON 对象
QJsonObject json;
json.insert("Name", "Qt");
json.insert("From", 1991);
json.insert("Cross Platform", true);

结果:(顺序相反)

代码语言:javascript
复制
{
    "Cross Platform": true,
    "From": 1991,
    "Name": "Qt"
}

解决办法:可以逆序调用insert方法插入值;或者用QJsonArray接口。

而在jsonArray中插入值的顺序与文件中的顺序是一致的,本身就是数组,自带下标(索引)。

插入值的代码:

代码语言:javascript
复制
// 构建 Json 数组 - Version
QJsonArray versionArray;
versionArray.append(4.8);
versionArray.append(5.2);
versionArray.append(5.7);

结果:(顺序一致)

代码语言:javascript
复制
"Version": [
        4.8,
        5.2,
        5.7
    ]

参考学习:

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年08月13日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 首先看一下这两个接口的定义:
  • 两个接口的对象中各自insert插入方法的区别:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档