gpt4 book ai didi

ios - 如何使用 JSONJoy 解析可选的 JSON 对象?

转载 作者:行者123 更新时间:2023-11-28 08:27:09 25 4
gpt4 key购买 nike

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 key “data” 是可选的。那么我如何使用相同的模型对象处理这两个响应??

最佳答案

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

来自文档

This also has automatic optional validation like most Swift JSON libraries.

//some randomly incorrect key. This will work fine and the property will just be nil.

firstName = decoder[5]["wrongKey"]["MoreWrong"].string

//firstName is nil, but no crashing!

这是我的例子,我是说明性的。我有一个复杂的对象集,其中我的顶级对象 (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
}
}

关于ios - 如何使用 JSONJoy 解析可选的 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39685384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com