JsonKit

一个 Swift 库,可以轻松地在 Swift 中读取和写入 JSON 数据对象,并将其转换为相应的 Swift 数据对象。

Swift Package Index


读取数据

要从 JSON 字符串中读取值,请使用 get 函数

let jsonString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}"

if let age = get(from: jsonString, key: "age", defaultValue: 10) as? Int {
    print("Age: \(age)")
}

此函数包含一个可选的 defaultValue 参数。 如果 JSON 数据存在问题或该值不存在,将返回此参数。


写入数据

要在 JSON 字符串中写入数据,请使用 set 函数

let jsonString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}"

if let updatedJsonString = set(in: jsonString, forKey: "age", value: 31) {
    print("Updated JSON String: \(updatedJsonString)")
}

如果 JSON 数据存在错误,则会返回 nil 值。 否则,将返回包含更新数据的新 JSON 字符串。