JSONJoyは、見つからない要素をnilにネイティブで設定するため、オプションで宣言してからnilをチェックするだけで済みます。
ドキュメントから
また、これは、ほとんどのスウィフトJSONライブラリのような自動オプションの検証を持っています。
//ランダムに間違ったキー。これは問題なく動作し、プロパティー はゼロになります。
のfirstName =デコーダ[5] [ "wrongKey"] [ "MoreWrong"]。文字列
// firstNameのがnil、ないクラッシュです!
これは私の例です。私は私の最上位レベルのオブジェクト(UserPrefs)が2次オブジェクトの配列(SmartNetworkNotificationとSmartNotificationTime)を持つ複雑なオブジェクトセットを持っています。
通知と時刻はどちらもオプションとして宣言されています。私が行うのは、2次オブジェクト配列を解析しようとした後で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
}
}