ios - 如何使用对象映射器解析以下 JSON

标签 ios swift objectmapper

这是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 值。

最佳答案

您的数据类型错误。您需要提供“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)!);

关于ios - 如何使用对象映射器解析以下 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35618318/

相关文章:

swift - 如何快速将数据转换为十六进制字符串

json - unirest 中的 Jackson 异常 : Serialization Impossible. 找不到 ObjectMapper 实现

ios - 如何从 Webview 的键盘获取完成按钮操作

ios - 从 AppDelegate 中的 NSMutableDictionary 清除几个推送通知

swift - 具有前景色的属性文本中的 NSTextAttachment 图像

ios - "' CGFloat ' is not convertible to ' UInt8 '"- CGFloat 包装问题

ios - Realm :更新对象而不更新列表

swift - 对象映射器将我的值设置为可选值

ios - 快速接触和碰撞检测

iphone - 从 NSArray 获取对象的索引?