首页 > 解决方案 > Swift 根据查询字符串过滤包中的 Json 文件

问题描述

我正在从应用程序包中加载一个 json 文件,如下所示:

if let fileURL = Bundle.main.url(forResource: "Picker.bundle/Data/MyCodes", withExtension: "json") {

    URLSession.shared.dataTask(with: fileURL) { (data, response, error) in

        do {

            if let d = data {

                let decodedLists = try JSONDecoder().decode([Codes].self, from: d)


                DispatchQueue.main.async {

                    self.code = decodedLists

                }

            } else {

                print("No Data")

            }

        } catch {

            print ("Error")

        }

    }.resume()

}

无论如何我可以应用过滤器,以便它只读取名称以某个字符串开头的代码

例子。

查询字符串将是“Can”,它将遍历 json 树并且只返回带有 Can i 他们的名字的孩子吗?

标签: jsonswiftswiftui

解决方案


解析JSON后,可以过滤结果,

struct Codes {
    var title: String
}

DispatchQueue.main.async {
   //filter codes if title starts with "Can"
   self.code = decodedLists.filter { $0.title.hasPrefix("Can") }
   //filter codes if title contains the substring "Can"
   self.code = decodedLists.filter { $0.title.contains("Can") }
}

推荐阅读