在Swift 4中过滤JSON

时间:2018-02-10 21:23:28

标签: json swift

我想过滤我的JSON而无法找到方法。 我的JSON:

{
"id": "3",
"nom": "Blancs sablons",
"description": "Plage gigantesque, très souvent des surfeurs à l'eau."
},
{
"id": "4",                                 // id to search
"nom": "Autre nom",                        // text to print
"description": "Encore une description"
},
{
"id": "5",
"nom": "Nom différent",
"description": "Et la dernière description"
},

我希望能够打印' Autre nom'通过调用

print(Spot[4].description)

其中4是id

所以我用构造函数尝试了这个struct Spot:

import Foundation
import MapKit

struct Spot : Decodable {
     let nom : String
     let description : String
     let id: String

init(nom: String, description: String, id: String, img1: String, latitude: String, longitude: String) {
    self.nom = nom
    self.description = description
    self.id = id
    self.img1 = img1
    self.latitude = latitude
    self.longitude = longitude
}
}

这解码JSON:

func getSpots(){
    guard let downloadURL = URL(string: "http://dronespot.fr/getSpot.php") else { return }
    URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
        guard let data = data, error == nil, urlResponse != nil else {
            print("Oops Call for Help")
            return
        }
        do {
            let decoder = JSONDecoder()
            let rates = try decoder.decode([Spot].self, from: data)
        } catch {
            print("Error after loading", error)
        }
        }.resume()
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您将获得一系列结果,因此您只需从数组中选择一个结果。

在我的测试代码中,我没有找到id为4的那个。

您可以使用过滤器高阶函数let rate = rates.filter { $0.id == "36" }

过滤数组

以下是我在Playground中用来测试的代码

//: Playground - noun: a place where people can play
import PlaygroundSupport
import UIKit

struct Spot : Decodable {
    let nom : String
    let description : String
    let id: String
}

func getSpots(){
    guard let downloadURL = URL(string: "http://dronespot.fr/getSpot.php") else { return }

    URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in

        guard let data = data, error == nil, urlResponse != nil else {
            print("Oops Call for Help")
            return
        }

        do {
            let decoder = JSONDecoder()
            let rates = try decoder.decode([Spot].self, from: data)
            let rate = rates.filter { $0.id == "36" }
            print(rate)
        } catch {
            print("Error after loading", error)
        }
    }.resume()
}

getSpots()

PlaygroundPage.current.needsIndefiniteExecution = true