0

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?

1
  • you miss details namespace Commented Aug 3, 2016 at 7:51

1 Answer 1

1

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"
...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks....if for some reason for example description is nil? all the details object returns nil ...how I can handle this?
changing the descriptionDetail field to an optional String? and mapping it with try descriptionDetail = map.optionalFrom("description") should do the trick

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.