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

标签 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)")
        }
    }
}

现在我想根据这个名字在搜索栏上搜索。在搜索直接提到核心数据属性的其他 View 时,我做了类似这样的事情,效果很好..

    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. 继续使用数据对象甚至 JSON 字符串作为模型是个坏主意。我建议你创建一些 Structs,使其符合 Codeable 协议(protocol),这样我就会使它易于使用并易于转换成 JSON,无论你想要什么。我强烈建议您考虑一下。

  2. JSONSerialization.jsonObject(with:) 将您的数据转换成字典,这样您就可以通过按键访问您想要的值,而不是枚举它:

像这样:

 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
   }
}

关于ios - 从 json 获取搜索栏中的过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48868214/

相关文章:

ios - 当我在该地区时,CLRegionState 是未知的

ios - 配置 tableview 单元格以将获取的对象传递给另一个 View (NSFetchedResultsController)

iphone - 将字符串属性添加到 CoreDataBooks

objective-c - 为什么 awakeFromInsert 被调用两次?

ios - 使用 dequeueReusableCellWithIdentifier 指定单元格时停止影响随机 UITableViewCells

ios - 解析中的 AlertViewController

iphone - 应用程序在 NSURLConnection 中崩溃

ios - 使用贝塞尔曲线绘制螺旋

objective-c - 如何在iOS中存储GPS坐标?

ios - 检查是否在核心数据中设置了属性?