【问题标题】:how to filter swiftyjson array如何过滤swiftyjson数组
【发布时间】:2018-03-22 13:54:27
【问题描述】:

我会尝试从堆栈溢出中获得的所有解决方案,但我运气不好。我将 JSON 响应存储在 [Any] 数组中,如下所示:

var json = JSON()
var arrClientType = [Any]()

self.json = JSON(value) //value is json data
self.arrClientType = self.json["client_type_data"].arrayValue

现在,我想过滤这个数组并在 tableview 中重新加载过滤后的数据。

[{
  "client_type_name" : "Asset Manager",
  "client_type_id" : 1
}, {
  "client_type_name" : "Broker Dealer",
  "client_type_id" : 5
}, {
  "client_type_name" : "Corporate",
  "client_type_id" : 8
}, {
  "client_type_name" : "Custodian and Prime Broker",
  "client_type_id" : 3
}, {
  "client_type_name" : "Diversified Financial Services Firms",
  "client_type_id" : 4
}, {
  "client_type_name" : "Fund Administrator",
  "client_type_id" : 6
}, {
  "client_type_name" : "Hedge Fund Manager",
  "client_type_id" : 2
}, {
  "client_type_name" : "Individual",
  "client_type_id" : 7
}]

我也试试这个:

 let filtered = JSON(self.arrList).arrayValue.filter({
                    $0["client_type_name"].arrayValue.map({ $0.stringValue }).contains("Broker Dealer")
                })
                print ("filterdData: \(filtered)")

但它给了我入口过滤器数组。

请帮帮我。

【问题讨论】:

  • 仅供参考 - SwiftJSON 或其他 3rd 方 JSON 库没有意义。使用新的 Swift 4 Codable 或使用 JSONSerialization。
  • 如果类型明显更具体,永远不要使用Any。您正在与强类型系统作斗争。

标签: ios swift swifty-json


【解决方案1】:

试试这个

     filtered = arrList.filter { $0["client_type_name"].stringValue.contains("Broker Dealer")  }

并将您的 self.arrlist 更改为字典类型的数组

 var arrList: [JSON]  = []
 var filtered :[JSON] = []

【讨论】:

    【解决方案2】:

    试试这个,您将能够过滤包含 “client_type_name”Broker Dealer的数据。

    let arrClientType = [["client_type_name":"Asset Manager" , "client_type_id":1] , ["client_type_name":"Broker Dealer" , "client_type_id":5] , ["client_type_name":"Corporate" , "client_type_id":8]]
    
    
    if let filteredData = arrClientType.filter({(($0 as? [String:Any])?["client_type_name"] as? String ?? "") == "Broker Dealer"}) as? [Any] {
    
                print(filteredData)
    
            }
    

    filteredData 是 arrayOfDictionary,其中包含 "client_type_name" 作为 Broker Dealer 的字典。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-14
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多