【问题标题】:iOS objectmapper, mapping json with arrayiOS objectmapper,用数组映射json
【发布时间】:2015-10-25 23:49:04
【问题描述】:

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

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

我会使用 swiftyJson

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

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

map["errors.code"]

它不起作用

编辑:我按照建议做了 Error 和 ErrorResponse 类,现在:

//...
    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)
     })
}

【问题讨论】:

  • 它给出的表达类型是友好的,没有更多的上下文。

标签: ios arrays json swift dictionary


【解决方案1】:

您的代码不起作用,因为属性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")

【讨论】:

  • 它部分工作:让 errorResponse = Mapper().map(operation.responseString!),然后我得到 ErrorResponse 的对象,如你所说的带有 [Error] 对象的数组。但是,当我执行类似 errorResponse.errors.first.code 的操作时,它会显示 nil。我要不要做一些额外的映射?
  • @Ammo 它对我有用,顺便说一句,我添加了一个测试来证明它有效
  • @Ammo 我用println(errorResponse?.errors![0].code) 测试了你的代码,它可以工作。我认为响应码是nil,或者你遗漏了什么
  • 是的,谢谢你的帮助,代码的问题是json实际上是这样的(代码不是作为字符串传递的):“错误”:[{“代码”:404,“消息": "错误的 id" } ]
【解决方案2】:

应该只传递 JSON-String 而不是你手写的字符串到 map 函数。

来自README

一旦您的类实现了 Mappable,Mapper 类就会为您处理所有其他事情:

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

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

所以你的情况可能是:

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

【讨论】:

    猜你喜欢
    • 2015-11-27
    • 2016-10-17
    • 1970-01-01
    • 2016-05-25
    • 2016-12-31
    • 1970-01-01
    • 2018-03-28
    • 2017-04-26
    • 1970-01-01
    相关资源
    最近更新 更多