2016-09-25 12 views
1

https://github.com/daltoniam/JSONJoy-SwiftJSONJoyを使用してオプションのJSONオブジェクトを解析する方法は?例えば

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

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

ここで、JSONのキー「データ」はオプションです。次に、同じモデルオブジェクトを使用して両方の応答を処理する方法はありますか?

答えて

0

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 
     } 
    } 
関連する問題