Latest 1.0.0
Homepage https://github.com/hinoppy/MappingJSON
License MIT
Platforms ios 8.0, osx 10.10, watchos 2.1, tvos 9.1, requires ARC
Authors

Build Status
Carthage compatible

MappingJSON is a framework written in Swift to make it easy to map JSON to your object.

Requirements

  • Swift 2.1 / Xcode 7.2
  • OS X 10.10 or later
  • iOS 8.0 or later
  • tvOS 9.1 or later
  • watchOS 2.1 or later

Installation

  • Carthage

    github "hinoppy/MappingJSON" ~> 1.0.0
  • CocoaPods
    use_frameworks!
    pod "MappingJSON", "~> 1.0.0"

Usage

Objects just need to implement Object protocol for mapping.

import MappingJSON

struct User: Object {
    var id: Int
    var name: String
    var email: String
    var age: Int?

    // Object protocol
    static func map(json: MappingJSON) throws -> User {
        return try User(
            id: json.value("id"),
            name: json.value("name"),
            email: json.value("email"),
            age: json.optionalValue("age")
        )
    }
}

Convert JSON to your object as below.

let rawJSON = [String: AnyObject] = [
    "id": 1,
    "name": "William",
    "email": "[email protected]",
    "age": 22
]

// initialize MappingJSON with raw JSON object
let json = MappingJSON(raw: rawJSON)

// pass your object type to 'map' function
let user = try? json.map(User)

print(user.email) // shows '[email protected]' to you console!

Transforms

You can transform raw values from JSON to whatever objects you like.
To transform, simply add a closure to second argument of value or optionalValue function.

struct User: Object {
    var id: Int
    var name: String
    var email: String
    var age: Int?
    var birthday: NSDate?

    // Object protocol
    static func map(json: MappingJSON) throws -> User {
        return try User(
            id: json.value("id"),
            name: json.value("name"),
            email: json.value("email"),
            age: json.optionalValue("age"),
            birthday: json.optionalValue("birthday", transform: dateTransform)
        )
    }
}
static let dateTransform = {(timestamp: NSTimeInterval) in
    NSDate(timeIntervalSince1970: timestamp)
}

License

MappingJSON is released under the MIT license.

Latest podspec

{
    "name": "MappingJSON",
    "version": "1.0.0",
    "summary": "A framework written in Swift for mapping JSON to object",
    "description": "MappingJSON is a framework written in Swift to make it easy to map JSON to your object.",
    "homepage": "https://github.com/hinoppy/MappingJSON",
    "license": "MIT",
    "authors": {
        "Shinya Hino": "[email protected]"
    },
    "platforms": {
        "ios": "8.0",
        "osx": "10.10",
        "watchos": "2.1",
        "tvos": "9.1"
    },
    "source": {
        "git": "https://github.com/hinoppy/MappingJSON.git",
        "tag": "1.0.0"
    },
    "source_files": "MappingJSON/*.swift",
    "requires_arc": true
}

Pin It on Pinterest

Share This