Home > Net >  Parse results from JSON to a list dynamically
Parse results from JSON to a list dynamically

Time:05-01

I do a JSON Request and get some information.

func parseJSON(poiData: Data) {
    let decoder = JSONDecoder()
    do {
        let decodedData = try decoder.decode(POIData.self, from: poiData)

        POIManager.POIname_One = decodedData.results[0].name
        POIManager.POIplaceid_One = decodedData.results[4].place_id
        POIManager.POIvicinity_One = decodedData.results[4].vicinity
        POIManager.POIlong_One = decodedData.results[0].geometry.location.lat
        POIManager.POIlat_One = decodedData.results[0].geometry.location.lng

        POIManager.POIname_Two = decodedData.results[1].name
        POIManager.POIplaceid_Two = decodedData.results[1].place_id
        POIManager.POIvicinity_Two = decodedData.results[1].vicinity
        POIManager.POIlong_Two = decodedData.results[1].geometry.location.lat
        POIManager.POIlat_Two = decodedData.results[1].geometry.location.lng
        
        POIManager.POIname_Three = decodedData.results[2].name
        POIManager.POIplaceid_Three = decodedData.results[2].place_id
        POIManager.POIvicinity_Three = decodedData.results[2].vicinity
        POIManager.POIlong_Three = decodedData.results[2].geometry.location.lat
        POIManager.POIlat_Three = decodedData.results[2].geometry.location.lng

        
    } catch {
        print(error)
    } 
}

In a different Swift file it put the results from the request in a list like this:

@IBAction func kategorieEins(_ sender: UIButton) {
       
        //Eigene Standort soll hier gezeigt werden/aktualisierter Standort
        locationManager.delegate=self

        let marker1 = GMSMarker()
        marker1.position = CLLocationCoordinate2D(latitude: POIManager.POIlong_One, longitude: POIManager.POIlat_One)
        marker1.title = POIManager.POIname_One
        marker1.snippet = "Marker1_0"
        marker1.map = mapView
        
        let marker2 = GMSMarker()
        marker2.position = CLLocationCoordinate2D(latitude: POIManager.POIlong_Two, longitude: POIManager.POIlat_Two)
        marker2.title = POIManager.POIname_Two
        marker2.snippet = "Marker2_0"
        marker2.map = mapView
        
        let marker3 = GMSMarker()
        marker3.position = CLLocationCoordinate2D(latitude: POIManager.POIlong_Three, longitude: POIManager.POIlat_Three)
        marker3.title = POIManager.POIname_Three
        marker3.snippet = "Marker3_0"
        marker3.map = mapView
   
    }

As you can see this whole thing is not dynamic it is static. I write down how many markers i want to have created. Is there a way to do this automatically? Especially when I dont know how much information there is in the json file and how many markers should be created.

CodePudding user response:

I solved it now. I tried:

    decodedData.results.forEach {
        print($0.name)
        print($0.place_id)
    }
  • Related