3

这是 JSON

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

我试图解析如下

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"]

  }
}

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

但它在解析时中断,发现 nil 值。

4

4 回答 4

3

您的数据类型错误。您需要提供“DoctorAvailablityResponseData”,但您提供了 ResponseDoctorAvailablity 用于映射。

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

例子

    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)!);
于 2016-02-25T05:25:07.757 回答
1

根据用户 JSON 'call_duration' 也是字符串类型。换线

var callDuration : Int?

至:

var callDuration : String?
于 2016-02-25T04:32:46.783 回答
0

你也可以将它们全部包装在一个“守卫”语句中,如果你得到一个 nil ,你可以传入 0 来表示一个项目是空的或没有长度。

于 2016-02-25T04:47:12.387 回答
0

您的 json 数据看起来像一个数组,其中第一个元素是字典。

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

除了将 call_duration 类型更改为 String 之外?您是否尝试过确保您实际上将字典而不是数组传递给 map 函数?尝试通过这个,看看它是否有效。

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

于 2016-02-25T06:11:04.273 回答