Reputation: 776
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 .
Upvotes: 3
Views: 1949
Reputation: 3661
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" }
Upvotes: 0
Reputation: 598
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)!);
Upvotes: 3
Reputation: 3395
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.
Upvotes: 0
Reputation: 4825
As per user JSON 'call_duration' is also string type. Change line
var callDuration : Int?
to:
var callDuration : String?
Upvotes: 1