HackySerializer 1.0.1

HackySerializer 1.0.1

测试已测试
Lang语言 SwiftSwift
许可协议 MIT
发布最新发布2017年1月
SwiftSwift 版本3.0.1
SPM支持 SPM

Andrii Chernenko 维护。



基于协议的序列化,适用于任何 Swift 类型

动机

该库是为满足将任何值简化、非侵入式序列化为 JSON 的需求而开发的,无需手动工作或子类化。

使用方法

  1. 指定对 HackySerializable 协议的遵守。
  2. 访问您值的 .serialized 属性。该属性类型为 AnyObject,包含根据值类型为 DictionaryArray
  3. 如有需要,使用 NSJSONSerialization 转换为 JSON
let 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
  ]
}

注意 SomeEnumSomeStuff 不需要遵守 HackySerializable

限制

  1. 性能:由于本库依赖反射,使用时需谨慎,否则可能会影响性能。
  2. 超类序列化:尚未实现。
  3. 字典键必须是 String 类型(尚不支持更通用的 Hashable 键)。
  4. 枚举:当前实现仅使用枚举情况名称。由于 Swift 反射的限制,不支持原始值,相关值可能以后会被支持。

反馈

该项目处于非常早期阶段。如果您有任何想法或发现了问题,请在此提交或通过 Twitter(@andrii_ch)联系我。