使用ObjectMapper从JSON反序列化为自定义对象

时间:2016-08-03 07:47:37

标签: json swift objectmapper

我在使用ObjectMapper将JSON数据反序列化为自定义对象时遇到了问题。

结构是这样的:

{
  "message": "",
  "payload": [
    {
      "details": {
        "id": "7758931",
        "description": "A description",
...

我的代码:

struct MyObject : Mappable
    {
        var message : String
        var payload : [MyDetail]?

        init(map: Mapper) throws
        {
            try message = map.from("message")
            payload = map.optionalFrom("payload") ?? nil
        }
    }

struct MyDetail : Mappable
{
    var detailId : String
    var descriptionDetail : String

    init(map: Mapper) throws
    {
        try detailId = map.from("id")
        try descriptionDetail = map.from("description")
    }
}

显然这是不正确的,因为有字典需要解析关键细节......

任何人都知道如何解析这个问题?

1 个答案:

答案 0 :(得分:1)

你需要一个包装细节的容器对象,因为它嵌套在details键下,如下所示:

struct MyObject : Mappable {
    var message : String
    var payload : [MyDetailContainer]?

    init(map: Mapper) throws {
        try message = map.from("message")
        payload = map.optionalFrom("payload") ?? nil
    }
}

struct MyDetailContainer : Mappable {
    var details: MyDetail

    init(map: Mapper) throws {
        try details = map.from("details")
    }
}

struct MyDetail : Mappable {
    var detailId : String
    var descriptionDetail : String

    init(map: Mapper) throws
    {
        try detailId = map.from("id")
        try descriptionDetail = map.from("description")
    }
}

假设json继续像这样:

{
  "message": "",
  "payload": [
    {
      "details": {
        "id": "7758931",
        "description": "A description"
      },
    },
    {
      "details": {
        "id": "7758932",
        "description": "Description #2"
...