Swift-在JSON文件中搜索特定值,然后在同一数组中提取整个字典数组

问题描述

这有点令人费解,但是我有一个包含邮政编码和城市数据的JSON文件,其格式如下:

[{
    "zip_code" : 32071,"latitude" : 30.036193,"longitude" : -82.932228,"city" : "O Brien","state" : "FL","county" : "Suwannee"
  },{
    "zip_code" : 32072,"latitude" : 30.36036,"longitude" : -82.25418,"city" : "Olustee","county" : "Baker"
  },{
    "zip_code" : 32073,"latitude" : 30.119884,"longitude" : -81.791546,"city" : "Orange Park","county" : "Clay"
  },{
    "zip_code" : 32079,"latitude" : 29.984882,"longitude" : -81.802221,"city" : "Penney Farms",{
    "zip_code" : 32080,"latitude" : "","longitude" : "","city" : "Saint Augustine","county" : "Saint Johns"
  },{
    "zip_code" : 46929,"latitude" : 40.556269,"longitude" : -86.490521,"city" : "flora","state" : "IN","county" : "Carroll"
  }]

我想在我的应用程序中执行的操作是给它提供一个邮政编码,然后从包含该邮政编码的数组中返回数据。因此,如果我正在寻找32071,它将在对象中返回ziplatitudelongitude等,然后可以通过{{ 1}}或object.city

尝试使用object.county进行此操作,但是没有用。我能够成功打印解码后的数据,只是无法进行下一步工作。

编辑:这是我的解码器:

getIndex(for:)

解决方法

您可以使用first(where:)-请注意,这会产生Optional

let result = try JSONDecoder().decode(Cities.self,from: jsonStr)

if let object = result.first(where: { $0.zipCode == 32071 }) {
    print(object.county) // prints "Suwannee"
}

如果要获得多个对象,可以使用filter

let objects = result.filter { $0.zipCode == 32071 }