测试已测试 | ✗ |
Lang语言 | SwiftSwift |
许可协议 | MIT |
发布最新发布 | 2017年1月 |
SwiftSwift 版本 | 3.0.1 |
SPM支持 SPM | ✗ |
由 Andrii Chernenko 维护。
基于协议的序列化,适用于任何 Swift 类型
该库是为满足将任何值简化、非侵入式序列化为 JSON 的需求而开发的,无需手动工作或子类化。
HackySerializable
协议的遵守。.serialized
属性。该属性类型为 AnyObject
,包含根据值类型为 Dictionary
或 Array
。NSJSONSerialization
转换为 JSONlet serialized = someStuff.serialized
let jsonData = try! NSJSONSerialization.dataWithJSONObject(serialized, options: [.PrettyPrinted])
let string = String(data: jsonData, encoding: NSUTF8StringEncoding)!
print(string)
enum SomeEnum {
case Case1, Case2
}
class SomeStuff {
let ok: String?
let omg: String?
let stuff: [Int?]
init(ok: String?, omg: String?, stuff: [Int?]) {
self.ok = ok
self.omg = omg
self.stuff = stuff
}
}
struct Person: HackySerializable {
let firstName: String
let secondName: String
let thingies: [SomeStuff]
let idSet: Set<Int>
let age: Int?
let age2: Int?
let someDict: [String: AnyObject?]
let anotherThingy: SomeStuff
let someEnumField: SomeEnum? = .Case1
let anotherEnumField: SomeEnum = .Case2
}
let person = Person(
firstName: "John",
secondName: "Doe",
thingies: [SomeStuff(ok: "111", omg: nil, stuff: [1, nil]), SomeStuff(ok: "222", omg: "22", stuff: [42, 100500])],
idSet: [1, 2],
age: 29,
age2: nil,
someDict: [ "hello": "world", "key": nil ],
anotherThingy: SomeStuff(ok: "ok", omg: nil, stuff: [])
)
结果 JSON
{
"age2" : null,
"anotherEnumField" : "Case2",
"secondName" : "Doe",
"someEnumField" : "Case1",
"thingies" : [
{
"stuff" : [
1,
null
],
"ok" : "111",
"omg" : null
},
{
"stuff" : [
42,
100500
],
"ok" : "222",
"omg" : "22"
}
],
"someDict" : {
"hello" : "world",
"key" : null
},
"age" : 29,
"firstName" : "John",
"anotherThingy" : {
"stuff" : [
],
"ok" : "ok",
"omg" : null
},
"idSet" : [
2,
1
]
}
注意 SomeEnum
和 SomeStuff
不需要遵守 HackySerializable
String
类型(尚不支持更通用的 Hashable
键)。该项目处于非常早期阶段。如果您有任何想法或发现了问题,请在此提交或通过 Twitter(@andrii_ch)联系我。