jerrygdm
jerrygdm

Reputation: 450

Deserializing from JSON to custom object using ObjectMapper

I have a problem deserializing JSON data to a custom object using ObjectMapper.

The structure is like this:

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

My code:

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")
    }
}

Obviously this is not correct since there is dictionary with a key details to parse...

Anyone have an idea how I can parse this?

Upvotes: 0

Views: 270

Answers (1)

nosyjoe
nosyjoe

Reputation: 561

You need a container object that wraps the details since it's nested under the details key, like this:

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")
    }
}

assuming that the json goes on like this like this:

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

Upvotes: 1

Related Questions