J2M 1.2.0

J2M 1.2.0

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Jan 2019
SPMSupports SPM

Maintained by Jiar.



J2M 1.2.0

J2M

codebeat badge

J2M is the json and model transformation framework that is implemented based on the Codable protocol of swift.

Requirements

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

Installation

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

Example

Import:

import J2M

Model:

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
  }

}

Encodable Encode:

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")
}

String Decode:

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")
}

Data Decode:

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")
}

License

J2M is released under the MIT license. See LICENSE for details.