簡體   English   中英

在Swift中解析JSON中的嵌套數組

[英]Parse Nested Array in JSON in Swift

我正在嘗試使用以下代碼和結構解析JSON:

    userApiService.getAllUsers { (responseDict:NSDictionary?, error:NSError?) -> Void in
   //Parse responseDict for the key "result"

      }

這是Json Structure

   {
        error = "";
        result =     (
                    {
                name = AnotherUser;
                password = AnotherPassword;
                userId = 1343;
            },
                    {
                name = TestUser;
                password = TestPassword;
                userId = 1344;
            },
                    {
                name = TestUser;
                password = TestPassword;
                userId = 1347;
            },
        );
        status = 200;
    }

我試過這樣的代碼:

 self.loadingIcon.endRefreshing()
            if let resultDict = responseDict["result"] as? NSArray {
                for userRecord in resultDict{
                    var userModel = User(userDict: userRecord as! NSDictionary)
                    self.tableData.append(userModel)
                }
            }
            self.tblView.reloadData()
        }

但這會導致錯誤"NSArray?" is not convertible to StringLiteralConvertible "NSArray?" is not convertible to StringLiteralConvertible如果我刪除可選項並添加! 強制解開閉包簽名,然后該錯誤消失。 但是,我曾見過一些實例,如果后端出了問題,我的應用就會崩潰。 所以我的問題是:

  1. 有沒有一種方法可以解析此JSON,並且仍將可選NSDictionary保留在閉包簽名中。

  2. 還是我只需要檢查字典是否不為零,然后繼續上面發布的代碼?

您可以通過添加“ ? ”來使用“零合並”來訪問“可選”字典中的鍵? 在字典變量及其下標之間,如下所示:

if let resultDict = responseDict?["result"] as? NSArray {
   // ...
}

使用這種語法,如果responseDict為nil,則評估將不會嘗試訪問密鑰。

最簡單的方法是使用庫。

1)您可以使用swiftyJSON。 它使用目標C JSON解析庫。 https://github.com/SwiftyJSON/SwiftyJSON

2)如果要使用純Swift解析器的庫,請嘗試JSONSwift。 github上的自述文件顯示了如何從JSON文件中檢索嵌套值。 並將其集成到項目中僅需要您導入一個文件。 https://github.com/geekskool/JSONSwift

嘗試使用objectForKey從字典中檢索數據,如下所示:

 self.loadingIcon.endRefreshing()
            if let resultDict = responseDict.objectForKey("result") as? NSArray {
                for userRecord in resultDict{
                    var userModel = User(userDict: userRecord as! NSDictionary)
                    self.tableData.append(userModel)
                }
            }
            self.tblView.reloadData()
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM