内容表

上一话题

文件和数据流函数

下一话题

布局管理

在 Qt 中支持 JSON

An overview of JSON support in Qt.

Qt 对处理 JSON 数据提供支持。JSON 是派生自 JavaScript 的对象数据编码格式,但现被广泛用作 Internet 数据交换格式。

The JSON support in Qt provides an easy to use C++ API to parse, modify and save JSON data. It also contains support for saving this data in a binary format that is directly “mmap”-able and very fast to access.

有关 JSON 数据格式的更多细节,可以找到在 json.org 和在 RFC-4627 .

概述

JSON 是结构化数据存储格式。它有 6 种基本数据类型:

  • bool

  • double

  • string

  • array

  • object

  • null

A value can have any of the above types. A boolean value is represented by the strings true or false in JSON. JSON doesn’t explicitly specify the valid range for numbers, but the support in Qt is limited to the validity range and precision of doubles. A string can be any valid unicode string. An array is a list of values, and an object is a collection of key/value pairs. All keys in an object are strings, and an object cannot contain any duplicate keys.

The text representation of JSON encloses arrays in square brackets ([ … ]) and objects in curly brackets ({ … }). Entries in arrays and objects are separated by commas. The separator between keys and values in an object is a colon (:).

简单 JSON 文档编码一个人、他/她的年龄、地址及电话号码看起来像:

{
    "FirstName": "John",
    "LastName": "Doe",
    "Age": 43,
    "Address": {
        "Street": "Downing Street 10",
        "City": "London",
        "Country": "Great Britain"
    },
    "Phone numbers": [
        "+44 1234567",
        "+44 2345678"
    ]
}
											

以上范例由 5 个键/值对的对象组成。二个值是字符串,一个是数字,一个是其它对象,最后一个是数组。

有效 JSON 文档是数组 (或对象),因此文档始终以方括号 (或花括号) 开头。

JSON 类

所有 JSON 类都是基于值的, 隐式共享类 .

Qt 中的 JSON 支持由这些类组成:

PySide2.QtCore.QJsonArray

QJsonArray 类封装 JSON 数组。

PySide2.QtCore.QJsonDocument

QJsonDocument 类提供读写 JSON 文档的办法。

PySide2.QtCore.QJsonObject

QJsonObject 类封装 JSON 对象。

QJsonObject.iterator

The QJsonObject::iterator class provides an STL-style non-const iterator for QJsonObject.

QJsonObject.const_iterator

The QJsonObject::const_iterator class provides an STL-style const iterator for QJsonObject.

PySide2.QtCore.QJsonParseError

QJsonParseError 类被用于在 JSON 剖析期间报告错误。

PySide2.QtCore.QJsonValue

The QJsonValue class encapsulates a value in JSON.

The QJsonValueRef class is a helper class for QJsonValue.