yingmu52
8/21/2017 - 4:29 PM

Demo Mapping json using ObjectMapper

Demo Mapping json using ObjectMapper


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let urlstring = "http://jsonplaceholder.typicode.com/posts"
        Alamofire.request(urlstring).responseJSON { (data) in
            let results = Mapper<Post>().mapArray(JSONObject: data.result.value)
            for post in results! {
                print(post.id)
                print(post.title)
                print(post.content)
            }
        }
    }
}


struct Post: Mappable {
    var id: Int
    var title: String
    var content: String
    var userId: Int
   
    init?(map: Map){
        id = 0
        title = ""
        content = ""
        userId = 0
    }
    
    mutating func mapping(map: Map) {
        id      <- map["id"]
        title   <- map["title"]
        content <- map["body"]
        userId  <- map["userId"]
    }
}