3

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 .

iAnurag
  • 9,286
  • 3
  • 31
  • 48
Mandeep Kumar
  • 776
  • 4
  • 18

4 Answers4

3

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)!);
Vignesh Kumar
  • 598
  • 4
  • 11
1

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

var callDuration : Int?

to:

var callDuration : String?
Aruna Mudnoor
  • 4,795
  • 14
  • 16
0

You could also wrap them all in a 'guard' statement that way if you do get a nil you can pass in 0 to represent that an item was empty or had no length.

Dan Leonard
  • 3,325
  • 1
  • 20
  • 32
0

Your json data looks like an array in which first element is a dictionary.

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

In addition to changing the call_duration type to String? have you tried ensuring that you are actually passing a dictionary and not an array to the map function? Try passing just this and see if it works.

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

Pradeep K
  • 3,671
  • 1
  • 11
  • 15