从json获取搜索栏中的过滤数据

时间:2018-02-19 14:23:39

标签: ios swift core-data uisearchbar

我正在为我的姓名文本字段分配名称。

for asd in orderDetails {

    if let jsonStr = asd.value(forKey: "customerJson") as? String {

        let data = sdf?.data(using: String.Encoding.utf8, allowLossyConversion: false)!

        do {
            if let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any] {
                for item in json {
                    if item.key == "first_Name" {
                        cell.nameLabel.text = item.value as? String //ASSIGNED HERE
                    }

                }
            }

        } catch let error as NSError {
            print("Failed to load: \(error.localizedDescription)")
        }
    }
}

现在我想根据此名称搜索搜索栏。在直接提到核心数据属性的其他视图中搜索时,我做了类似的工作,但工作正常。

    filtered = self.newProdDetails.filter({( data : NewProduct) -> Bool in
        return (data.name?.lowercased().contains(searchText.lowercased()))! //Here the entity NewProduct has an attribute name
    })

但是在当前场景中,该属性是一个名为customer_json的属性,它是一个像这样的json字符串。

customer_json={
  "mobile_number”:”9876543210”,
  "first_name”:”testName”,
  "last_name”:”testLastName”,
  "seller_id":"93"
} 

如何在搜索参数

中提及first_name

1 个答案:

答案 0 :(得分:0)

  1. 继续使用Data对象甚至JSON字符串作为您的模型是个坏主意。我建议你创建一些Structs,使其符合Codeable协议,这样我就可以轻松使用并轻松转换为任何你想要的JSON。我强烈建议你考虑一下。

  2. JSONSerialization.jsonObject(with:)将您的数据转换为字典,因此您可以通过密钥访问所需的值,而不是枚举它:

  3. 像这样:

     if let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
        let name = json["first_Name"] {
         cell.nameLabel.text = name
     }
    

    绝对可以以同样的方式访问您的数据:

     orderDetails.filter{ asd in  
        if 
            let jsonStr = asd.value(forKey: "customerJson") as? String,
            let data = sdf?.data(using: String.Encoding.utf8, allowLossyConversion: false)
            let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
            let name = json["first_Name"],
            name == cell.nameLabel.text { 
                 return true 
       } else {
           return false
       }
    }
    
相关问题