J2M 1.2.0

J2M 1.2.0

测试测试状态
语言语言 SwiftSwift
许可协议 MIT
版本最新版本2019 年 1 月
SPM支持 SPM

Jiar 维护。



J2M 1.2.0

J2M

codebeat badge

J2M 是一个基于 Swift 的 Codable 协议实现的 json 和模型转换框架。

要求

  • iOS 8.0+ / macOS 10.9+ / tvOS 9.0+
  • Xcode 10.0+
  • Swift 4.2+

安装

CocoaPods

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target '<Your Target Name>' do
  pod 'J2M', '~> 1.2.0'
end

例子

导入

import J2M

模型

struct Article: Codable {

  enum `Type`: String, Codable {
    case story = "story"
    case job   = "job"
  }

  let id: Int
  let deleted: Bool
  let type: Type
  let title: String
  let text: String?
  let authorId: Int
  let authorName: String
  let created: TimeInterval
  let comments: [Int]?

  // Key Mapping
  private enum CodingKeys : String, CodingKey {
    case id = "articleId", deleted, type, title, text, authorId, authorName, created = "createTime", comments
  }

}

可编码 编码

let article = Article(id: 1, deleted: false, type: .story, title: "title", text: "content", authorId: 1, authorName: "Jiar", created: Date().timeIntervalSince1970, comments: [1, 2, 3])

if let json = article.j2m.toJson() {
  // {"comments":[1,2,3],"deleted":false,"authorId":1,"title":"title","text":"content","authorName":"Jiar","type":"story","articleId":1,"createTime":1503495092.778208}
  print("\n\(json)\n")
}

字符串 解码

let json =
  """
  {"deleted":false,"authorId":2,"title":"title2","text":"content2","authorName":"Jiar","type":"job","articleId":1,"createTime":1503384985.8531871}
  """

if let article = json.j2m.toModel(type: Article.self) {
  // Article(id: 1, deleted: false, type: J2M_Demo.Article.Type.job, title: "title2", text: Optional("content2"), authorId: 2, authorName: "Jiar", created: 1503384985.8531871, comments: nil)
  print("\n\(article)\n")
}

数据 解码

let data =
  """
  {"deleted":true,"authorId":3,"title":"title3","authorName":"Jiar","type":"story","articleId":1,"createTime":1503384985.8531871,"comments":[4,5]}
  """
  .data(using: .utf8)!
		
if let article = data.j2m.toModel(type: Article.self) {
  // Article(id: 1, deleted: true, type: J2M_Demo.Article.Type.story, title: "title3", text: nil, authorId: 3, authorName: "Jiar", created: 1503384985.8531871, comments: Optional([4, 5]))
  print("\n\(article)\n")
}

许可

J2M 采用 MIT 许可证发布。详细信息参见 LICENSE。