Search code examples
jsonswiftobjectmapper

Alphanumeric ID not mapping but gives Nil output


So, I am having issues correctly mapping my ID attribute from my json data. I am not really sure what I am missing because I was able to successfully map a similar attribute which also has similar data.

Here is my model I created:

import Foundation
import ObjectMapper

enum ItemsModelEnum: String {

    case kind = "kind"
    case etag = "etag"
    case id = "id"

}

struct ItemsModel: Mappable {

    var kind: String!
    var etag: String!
    var id: String!


    init?(map: Map) {

    }

    init(kind: String, etag: String, id: String) {
        self.kind = kind
        self.etag = etag
        self.id = id
    }

    init() {
        self.kind = ""
        self.etag = ""
        self.id = ""

    }

    mutating func mapping(map: Map) {

        kind <- map[ItemsModelEnum.kind.rawValue]
        etag <- map[ItemsModelEnum.etag.rawValue]
        id <- map[ItemsModelEnum.id.rawValue]
    }

}

And this is my mapping code I have used:

do {
    if let data = data,
        let videoData =  Mapper<ItemsModel>().map(JSONObject: try JSONSerialization.jsonObject(with: data, options: [])) {

            completionHandler(videoData,(response as! HTTPURLResponse), error)
            print("videoData Received Successfully")
        }
} catch {
    completionHandler(nil,(response as! HTTPURLResponse), error)
    print("Error parsing json get video data: ", error.localizedDescription)
}

The following is the json data I am trying to map:

{
    "kind": "youtube#playlistItemListResponse",
    "etag": "\"xxxxxxxxxxxxx"",
    "pageInfo": {
        "totalResults": 4,
        "resultsPerPage": 10
    },
    "items": [
        {
            "kind": "youtube#playlistItem",
            "etag": "\"xxxxxx"",
            "id": "xxxxxx",

        }
}

What is interesting is that the etag attribute is being mapped successfully but not so the id attribute as it gives me nil when I get a response.

Any idea what could be the cause?

In my Xcode, when I print my object I am getting the following output:

Printing description of videoData:

▿ ItemsModel
  ▿ kind : Optional<String>
    - some : "youtube#playlistItemListResponse"
  ▿ etag : Optional<String>
    - some : "\"Xxxxxxxxx""
  - id : nil

Solution

  • You try to get id, but you have pageInfo or items there. You need to go deeper and get with path ["items"][0]["id"]

    You try to get id directly from object, but your needed object located deeper.

    You need to create 3 structs for main object, for object with key "pageInfo", for objects with key "items".