iOS objectmapper,用数组映射json

时间:2015-08-03 18:49:33

标签: ios arrays json swift dictionary

我有一个简单的问题:如何使用Hearst-DD / ObjectMapper将这样的json响应转换为对象

{
   "errors": [
      {
         "code": "404",
         "message": "Wrong id"
      }
    ]
}

使用swiftyJson我做

json["errors"][0]["code"]

但是如何使用objectmapper呢?我试过这个:

map["errors.code"]

它不起作用

编辑:我做了错误和ErrorResponse clasess,如建议,现在:

//...
    let fullAddress = mainAddress + additionalAddr
    var parameters = ["email":email]

    manager.GET( fullAddress,
        parameters: parameters,
        success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
            //here is success, i got it done with user mapping
            callback(success: true)
        },
        failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in

            let errorResponse = Mapper<ErrorResponse>().map(operation.responseString!)


            println(errorResponse!) //this prints: MyApp.ErrorResponse
            println(errorResponse?.errors!) //this prints: Optional([MyApp.Error]) 
            println(errorResponse?.errors![0]) //this prints:Optional(MyApp.Error)
            println(errorResponse?.errors![0].code) //<- this is nil :(
           // how to get the code mapped ?
            callback(success: false)
     })
}

2 个答案:

答案 0 :(得分:3)

您的代码不起作用,因为属性errors是一个数组,而ObjectMapper尝试将其转换为对象。

对于您提供的JSON,正确的答案如下:

class Error: Mappable, Printable {
    var code: String?
    var message: String?

    init() {}

    class func newInstance() -> Mappable {
        return Error()
    }

    func mapping(map: Map) {
        self.code <- map["code"]
        self.message <- map["message"]
    }

    var description: String {
        get {
            return Mapper().toJSONString(self, prettyPrint: false)!
        }
    }
}

class ErrorResponse: Mappable, Printable {
    var errors: [Error]?

    init () {}

    class func newInstance() -> Mappable {
        return ErrorResponse()
    }

    func mapping(map: Map) {
        self.errors <- map["errors"]
    }

    var description: String {
        get {
            return Mapper().toJSONString(self, prettyPrint: false)!
        }
    }
}

测试:

    let json = "{\"errors\": [{\"code\": \"404\",\"message\": \"Wrong id\"}]}"

    let errorResponse = Mapper<ErrorResponse>().map(json)

    println("errorResponse: \(errorResponse?.description)")

    if let errors = errorResponse?.errors {
        println("errors: \(errors.description)")
        println("errors[0] \(errors[0])")
        println("errors[0].code \(errors[0].code)")
        println("errors.first!.message \(errors.first!.message)")
    }

输出:

errorResponse: Optional("{\"errors\":[{\"message\":\"Wrong id\",\"code\":\"404\"}]}")
errors: [{"message":"Wrong id","code":"404"}]
errors[0] {"message":"Wrong id","code":"404"}
errors[0].code Optional("404")
errors.first!.message Optional("Wrong id")

答案 1 :(得分:0)

应该只传递JSON-String而不是你手写的地图函数。

来自README

  

一旦你的类实现了Mappable,Mapper类就会为你处理其他一切:

     

将JSON字符串转换为模型对象:

let user = Mapper<User>().map(JSONString)

所以你的场景可能是:

let error = Mapper<Error>().map(json)