生成规则
SwiftyModel 如何推断类型、命名属性,以及处理数组和嵌套。本页示例均由 SwiftyModel 使用默认设置生成。
基本类型
| JSON 值 | Swift 类型 | 读取方式 |
|---|---|---|
| 字符串 | String | stringValue |
| 整数 | Int | intValue |
| 小数 | Double | doubleValue |
true / false | Bool | boolValue |
| 对象 | 嵌套类型 | Type(json:) |
null | Any;打开 Codable 时为 JSON | object / 原始 JSON |
属性按 JSON 键的字母顺序排列。
嵌套对象
每个嵌套对象都会生成一个嵌套类型,名称取自它的键,并转换成首字母大写的驼峰形式:profile 生成 Profile,house_name 生成 HouseName。嵌套类型写在外层类型内部。
对象最多展开 10 层。更深的对象不再生成类型,而是保留为 JSON,数据不会丢失。
数组
- 元素类型一致时,生成对应的数组类型,如
[String]。 - 多维数组逐层推断,如
[[Int]]。 - 同时有整数和小数时,统一为
[Double]。 - 对象数组中每个对象的键和值类型都相同时,生成一个元素类型;名称取自数组的键,如
items生成Items。 - 元素类型不一致,或对象结构不同时,使用
[Any];打开 Codable 时使用[JSON]。
输入:
{
"matrix": [[1, 2], [3, 4]],
"scores": [1, 2.5],
"mixed": [1, "a"],
"items": [{ "id": 1 }, { "id": 2 }],
"note": null
}结果:
import Foundation
import SwiftyJSON
struct Report {
struct Items {
let id: Int
init(json: JSON) {
id = json["id"].intValue
}
}
let items: [Items]
let matrix: [[Int]]
let mixed: [Any]
let note: Any
let scores: [Double]
init(json: JSON) {
items = json["items"].arrayValue.map { Items(json: $0) }
matrix = json["matrix"].arrayValue.map { $0.arrayValue.map { $0.intValue } }
mixed = json["mixed"].arrayValue.map { $0.object }
note = json["note"].object
scores = json["scores"].arrayValue.map { $0.doubleValue }
}
}打开 Codable 后,无法确定类型的值改用 SwiftyJSON 的 JSON 类型,因为 Any 不能遵循 Codable:
import Foundation
import SwiftyJSON
struct Report: Codable {
let mixed: [JSON]
let note: JSON
private enum CodingKeys: String, CodingKey {
case mixed
case note
}
init(json: JSON) {
mixed = json["mixed"].arrayValue.map { $0 }
note = json["note"]
}
}顶层是数组
JSON 顶层是对象数组时,“Model名称”用作元素类型的名称。例如输入两个 { "id": …, "name": … } 组成的数组,Model名称为 Item:
import Foundation
import SwiftyJSON
struct Item {
let id: Int
let name: String
init(json: JSON) {
id = json["id"].intValue
name = json["name"].stringValue
}
}读取整个数组时,对每个元素调用 Item(json:):json.arrayValue.map { Item(json: $0) }。
顶层是基本值数组时,生成类型别名。输入 [1, 2, 3],Model名称为 Scores:
import Foundation
import SwiftyJSON
typealias Scores = [Int]属性命名
- 驼峰命名:
user_name变成userName(可在设置中关闭)。 - 关键字:与 Swift 关键字同名的键会加上前缀或后缀,默认是前缀
key,如class变成keyClass。 - 数字开头:如
2nd_place,始终加前缀。 - 重名:两个键转换后得到相同的属性名时,原本就是这种拼写的键保留名称,另一个加上编号,如
userName2。 - 特殊字符:空格、连字符等不能出现在 Swift 标识符中的字符会被去掉或转换。
无论属性名怎样变化,读取时用的始终是原始的 JSON 键;打开 Codable 时,CodingKeys 也会映射回原始键。
{
"self": true,
"class": "A",
"2nd_place": "Bob",
"userName": "Ada",
"user_name": "ada"
}import Foundation
import SwiftyJSON
struct Player {
let key2NdPlace: String
let keyClass: String
let keySelf: Bool
let userName: String
let userName2: String
init(json: JSON) {
key2NdPlace = json["2nd_place"].stringValue
keyClass = json["class"].stringValue
keySelf = json["self"].boolValue
userName = json["userName"].stringValue
userName2 = json["user_name"].stringValue
}
}