BSON

一个快速的 BSON 库,完全符合 BSON 规范的整个测试套件。该库按需解析二进制数据,延迟复制直到最后一刻。

BSON 的解析和生成遵循 BSON 规范 1.1 版本的规定。

请务必阅读我们的完整文档API 参考

安装

BSON 使用 Swift Package Manager。将 BSON 添加到您的 Package.swift 文件中的依赖项。

.package(url: "https://github.com/orlandos-nl/BSON.git", from: "8.0.0")

另外,不要忘记将 "BSON" 添加为您的目标的依赖项。

基本用法

使用字典字面量创建文档

var userDocument: Document = [
  "username": "Joannis",
  "online": true,
  "age": 20,
  "pi_constant": 3.14,
  "profile": [
    "firstName": "Joannis",
    "lastName": "Orlandos"
  ]
]

let favouriteNumbers: Document = [1, 3, 7, 14, 21, 24, 34]

userDocument["favouriteNumbers"] = favouriteNumbers

像访问 Swift 数组一样访问数组中的值,像访问字典一样访问对象中的值。

let favouriteNumber = favouriteNumbers[0]
let usernameValue = userDocument["username"]

轻松提取类型

let username = String(userDocument["username"]) // "Joannis"
let isOnline = Bool(userDocument["online"]) // true
let age = Int(userDocument["age"]) // 20
let pi = Double(userDocument["pi_constant"]) // 3.14

轻松链式使用下标查找结果,如下所示,使用这个 JSON 结构(假设它以 BSON 表示)

{
  "users": [
    {
      "username": "Joannis",
      "profile": {
        "firstName": "Joannis",
        "lastName": "Orlandos"
      }
    },
    {
      "username": "Obbut",
      "profile": {
        "firstName": "Robbert",
        "lastName": "Brandsma"
      }
    }
  ]
}
let obbutLastName = String(object["users"][1]["profile"]["lastName"]) // "Brandsma"

嵌套文档

复杂的数组和字典字面量可能会使 Swift 类型系统感到困惑。如果发生这种情况,请将字面量显式声明为 Document 类型

var userDocument: Document = [
  "username": "Joannis",
  "online": true,
  "age": 20,
  "pi_constant": 3.14,
  "profile": [
    "firstName": "Joannis",
    "lastName": "Orlandos",
    "pets": [
        [
          "name": "Noodles",
          "type": "Parrot"
        ] as Document,
        [
          "name": "Witje",
          "type": "Rabbit"
        ]
      ] as Document
    ] as Document
]

Codable

可以从 SwiftNIOByteBufferFoundation.Data 实例化 Document。您可以使用 .validate() 函数手动验证此文档的格式。这将也会指定在何处发现数据损坏。

如果将 DocumentPrimitive 传递到 BSONDecoder 中,如果格式匹配,则可以解码任何 Decodable 类型。同样,BSONEncoder 可以将您的 Swift 类型编码为 Document