2017-05-22 103 views
0

我在swift代碼中成功使用parse JSON data但我想打印具有特定值的數據。眼下代碼vc.packages打印所有,但我只想打印誰是那些:過濾JSON數據並打印它

  • 「TYPECODE」充滿「 validTo」有一個值,「stateCode」是有效的

如何在我的代碼中檢查並分別打印?

func unzipPackage() { 

    let vc = storyboard?.instantiateViewController(withIdentifier: "LoadingScreenController") as! LoadingScreenController 

    let popup = STPopupController(rootViewController: vc) 
    popup.style = .formSheet 
    popup.hidesCloseButton = false 
    popup.navigationBarHidden = true 
    popup.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) 
    popup.containerView.layer.cornerRadius = 4 
    popup.present(in: self, completion: { 

     DemosClient.sharedInstance.requestDataPackage() 
      .then { response -> Void in 

       vc.contentSizeInPopup = CGSize(width: 600, height: 800) 
       vc.landscapeContentSizeInPopup = CGSize(width: 600, height: 800) 


       vc.titles = (self.parseJSON(response: response)) 
       print(vc.titles) 
       vc.packages = response["results"] as? [[String:Any]] ?? [] 


       print(vc.packages) 

      } 
      .catch { error in 

       print(error) 
     } 

     vc.loadData() 
     vc.startTimer() 


    }) 
+0

「validTo」有一個值嗎? –

+0

@NiravD因爲它不是空的。例如在JSON解析中:validTo「:,它有一個空值,」validTo「:2017-05-11T07:57:07Z這個有一個值。 – habed

+0

你想從這個字典數組中獲得數組contentUrl嗎? –

回答

2

對於您可以filterresults陣列,然後分配的filter結果packages

let results = response["results"] as? [[String:Any]] ?? [] 
vc.packages = results.filter { 
    return ($0["typeCode"] as? String == "FULL") && 
      ($0["validTo"] != nil) && 
      ($0["stateCode"] as? String == "valid") 
} 
+0

我試過了,但是我收到一個錯誤,在這一行中索引超出範圍cell.textLabel?.text = packages [indexPath.row] [「name」] as!字符串 cell.detailTextLabel?.text =包[indexPath.row] [「releaseNotes」] as!字符串 – habed

+1

@hamedab​​edini你是什麼意思的indexOutOfRange如果你正在工作表或集合,然後確保你正在返回數組數,而不是一些靜態值 –

+0

我修復了這個問題,但是wh我運行代碼,它實際上不會過濾它。 – habed

1

您需要解析字典數組並檢查鍵和對應的值。這段代碼應該做到這一點。我沒有測試過,但應該可以正常工作。

vc.packages = response["results"] as? [[String:Any]] ?? [] 

let filteredPackages = [[String:Any]]() 
for package in vc.packages { 
    guard let typeCode = package["typeCode"] as? String, typeCode == "FULL" else { continue } 
    guard let stateCode = package["stateCode"] as? String, stateCode == "valid" else {continue} 
    guard let validTo = package["validTo"] as? String, validTo != "" else {continue} 
    filteredPackages.append(package) 
} 

print(filteredPackage) 
+0

謝謝Dávid,它工作並感謝學習曲線。 – habed