Iatheto

Iatheto 是一个极简的 JSON 框架,可以与 Apple 的 Codable 进行序列化和反序列化。现在已经有很多类似的框架,但 Iatheto 是最古老的框架之一——它早于 Codable——并且实现非常小巧。

Iatheto 仅支持 JSON 直接支持的那些类型,不支持其他类型。例如,要处理日期,您必须首先将其转换为字符串。

字面量

像大多数现代 Swift JSON 框架一样,Iatheto 支持常用的字面量赋值

var json: JSON = nil // Produces JSON.null
json = "json" // Produces JSON.string("json")
json = ["array": [1, 2, 3]] // Produces JSON.object(["array": JSON.array([1, 2, 3])])

属性

Iatheto 具有可空属性——getter 和 setter——可用于获取类型化的值。

let json: JSON = "json"
let s = json.string // If json is JSON.string, then s will be "json", otherwise nil. 

nil 赋值给这些属性之一会将接收者更改为 JSON.null

var json: JSON = "json"
json.string = nil // json is now JSON.null

下标

Iatheto 具有你所期望的下标

let json: JSON = ["foo": ["bar"]]
let s = json["foo"]?[0]?.string // If the types work out s will be "bar", otherwise nil.

可以通过下标进行赋值。 将 nil 赋值给数组下标会产生 JSON.null。 但是,通过对象下标赋值 nil 会从底层对象中删除该条目。 要专门设置为 JSON.null,请赋值该特定值。

var json: JSON = ["foo": ["bar"]]
json["foo"]?[0] = nil // Produces {"foo": [null]}
json["foo"] = .null // Produces {"foo": null}
json["foo"] = nil // Produces {}

在下标赋值期间,如果底层值不是数组或对象,它会变成数组或对象

var json: JSON = nil
json["foo"] = "bar" // Produces {"foo": "bar"}
json["foo"]?.int = 3 // Produces {"foo": 3}

编码

Iatheto 的 JSON 类型支持通过多种字面量进行初始化,因此语法很自然。

let json: JSON = ["first_name": "Murray", "last_name": "Rothbard", "born": 1926, "died": 1995]
let encoder = JSONEncoder()
let data = try encoder.encode(json)

解码

解码和编码一样简单直接

let decoder = JSONDecoder()
let json = try decoder.decode(JSON.self, from: data)

什么是 Iatheto?

"Iatheto" 来自希腊语 ἰαθήτω,意思是“她将被治愈”,而 ἰαθήτω 又来自动词 ἰάομαι,意思是“治愈”。 这个动词是名称 Ἰάσων “Jason” 的起源。