【问题标题】:How to parse a optional JSON object using JSONJoy?如何使用 JSONJoy 解析可选的 JSON 对象?
【发布时间】:2016-09-25 09:34:13
【问题描述】:

https://github.com/daltoniam/JSONJoy-Swift 例如:

JSON1 = {
"message": "Sorry! Password does not match.",
"code": "4"
}

JOSN2 = {
"data": {
"id": 21
},
"message": "Signup Successful.",
"code": "1"
},

这里的 json 键“数据”是可选的。那么如何使用同一个模型对象来处理这两个响应呢??

【问题讨论】:

    标签: ios json swift parsing


    【解决方案1】:

    JSONJoy 原生将未找到的元素设置为 nil,您只需将它们声明为可选,然后在使用它们之前检查 nil。

    来自文档

    这也像大多数 Swift JSON 库一样具有自动可选验证。

    //一些随机错误的键。这将工作正常和财产 将只是零。

    firstName = 解码器[5]["wrongKey"]["MoreWrong"].string

    //firstName 为 nil,但不会崩溃!

    这是我的示例,我的示例是说明性的。我有一个复杂的对象集,其中我的顶级对象(UserPrefs)具有辅助对象数组(SmartNetworkNotification 和 SmartNotificationTime)。

    请注意,通知和时间都被声明为可选。我所做的是在尝试解析辅助对象数组后检查 nil。如果没有 nil 检查,则尝试在已解析列表上进行迭代失败,因为它的 nil。使用 nil 检查,如果它是空的,它只会移动过去。

    这对我有用,但尚未经过深入测试。 YMMV!好奇别人是怎么处理的。

    struct UserPrefs: JSONJoy {
        var notifications: [SmartNetworkNotification]?
        var times: [SmartNotificationTime]?
    
        init(_ decoder: JSONDecoder) throws {
            // Extract notifications
            let notificationsJson = try decoder["notifications"].array
            if(notificationsJson != nil){
                var collectNotifications = [SmartNetworkNotification]()
                for notificationDecoder in notificationsJson! {
                    do {
                        try collectNotifications.append(SmartNetworkNotification(notificationDecoder))
                    } catch let error {
                        print("Error.. on notifications decoder")
                        print(error)
                    }
                }
                notifications = collectNotifications
            }
    
            // Extract time of day settings
    
            let timesJson = try decoder["times"].array
            if(timesJson != nil){
                var collectTimes = [SmartNotificationTime]()
                for timesDecoder in timesJson! {
                    do {
                        try collectTimes.append(SmartNotificationTime(timesDecoder))
                    } catch let error {
                        print("Error.. on timesJson decoder")
                        print(error)
                    }
                }
                times = collectTimes
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2015-12-30
      • 2016-02-13
      • 2012-09-28
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      相关资源
      最近更新 更多