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