Search code examples
iosjsonswiftobjectmapper

How to handle escaped emebed json within another JSON using Swift ObjectMapper


I'm trying to map a json string back to my data model using ObjectMapper. Below is my JSON string i'm trying:

{
  "UserName":"test",
  "StudentNo":71129,
  "Activity":{
    "name":"test name",
    "semester":"1",
    "activityHistory":"{ \"id\": \"111111\", \"items\": [ { \"datetime\": \"201923022016\", \"mediaFormat\": \"online\" } ,{ \"datetime\": \"201923022016\", \"mediaFormat\": \"online\" } ,{ \"datetime\": \"201923022016\", \"mediaFormat\": \"online\" } ]}"
  }
 }

The embedded json within the json payload is coming from an external API and i have no control over it.

My Model classes:

import UIKit import ObjectMapper

    class studentModel: Mappable {
        var UserName: String?
        var StudentNo : String?
        var Activity : [ActivityModel]?

        init() {}

        required init?(_ map: Map) {
        }

        // Mappable
        func mapping(map: Map) {
            UserName             <- map["userName"]
            StudentNo         <- map["stNO"]
            Activity            <- map["Activity"]
        }
    }


    class ActivityModel: Mappable {
        var name: String?
        var semester : Int?
        var activityHistory: String?

        init() {}

        required init?(_ map: Map) {
        }

        // Mappable
        func mapping(map: Map) {
            name             <- map["name"]
            semester         <- map["semester"]
            activityHistory  <- map["activityHistory"]
        }
    }

I don't seem to be able to map the json string successfully and know that the issue is with the activityHistroy since if i change the value of that field to something simple ("TEST") and change my model from var Activity : [ActivityModel]? to var Activity : String? I can get the whole thing mapped.

To Map to object:

var studentModel = Mapper<studentModel>().map(JSON)!

studentModel.Activity is always nil after the above! Can anyone see what i am doing wrong?


Solution

  • var Activity : [ActivityModel]? means it expects an array of ActivityModel but Json you posted it is not an Array. Change var Activity : [ActivityModel]? to var Activity : ActivityModel?.