Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse following JSON using object mapper

This is the JSON

[{ "start_hour": "08:00:00", "end_hour": "10:00:00", "call_duration": "30" }]

I tried to parse as follows

class DoctorAvailablityResponseData: Mappable {
var startDateHour : String?
var callDuration : Int?
var endDateHour : String?
required init?(_ map: Map){

}

func mapping(map: Map) {
    callDuration <- map["call_duration"]
    endDateHour <- map["end_hour"]
    startDateHour <- map["start_hour"]

  }
}

and

let user = Mapper<ResponseDoctorAvailablity>().map(response.result.value)

But it breaks while parsing , found nil value .

like image 677
Mandeep Kumar Avatar asked Dec 22 '25 03:12

Mandeep Kumar


2 Answers

Your data type is wrong. You need to give "DoctorAvailablityResponseData", but you gave ResponseDoctorAvailablity for mapping.

    let user = Mapper<ResponseDoctorAvailablity>().map(response.result.value)

Example

    class Doctor: Mappable {
        var startDateHour : String?
        var callDuration : String?
        var endDateHour : String?
        required init?(_ map: Map){

        }

        func mapping(map: Map) {
            callDuration <- map["call_duration"]
            endDateHour <- map["end_hour"]
            startDateHour <- map["start_hour"]

        }
    }

    // Sample Response
    let response : NSMutableDictionary = NSMutableDictionary.init(object: "08:00:00", forKey: "start_hour");
    response.setValue("10:00:00", forKey: "end_hour");
    response.setValue("30", forKey: "call_duration");

    // Convert response result to dictionary type. It is very easy.
    let userdic = Mapper<Doctor>().map(response) // Map to correct datatype.
    NSLog((userdic?.callDuration)!);

    // If you result is nested object. you will easily get zero index position object and parse it.
    let nestedObjectArray :NSArray = NSArray.init(array: [response]);

    let userArray = Mapper<Doctor>().map(nestedObjectArray[0])


    NSLog((userArray?.callDuration)!);
like image 171
Vignesh Kumar Avatar answered Dec 23 '25 19:12

Vignesh Kumar


As per user JSON 'call_duration' is also string type. Change line

var callDuration : Int?

to:

var callDuration : String?
like image 21
Arun Ammannaya Avatar answered Dec 23 '25 19:12

Arun Ammannaya