swiftxcodensarraynsdictionarynsjsonserialization

Cannot iterate through array inside array of dictionaries


I'm having trouble parsing a response into workable objects in swift.

Basically, this is the response I get (simplified data for viewing purposes)

"[{\"CO2\":0,\"Places\":[{\"Name\":\"RT(Esc. Sec.)\",\"Code\":\"ST_RT\",\"Type\":0,\"CoordX\":41.176750183105469,\"CoordY\":-8.5490522384643555,\"Provider\":\"ST\",\"Lines\":null},{\"Name\":\"Esc.Sec RT\",\"Code\":\"ST_RT2\",\"Type\":0,\"CoordX\":41.175251007080078,\"CoordY\":-8.54929256439209,\"Provider\":\"ST\",\"Lines\":null},{\"Name\":\"SM\",\"Code\":\"ST_SM\",\"Type\":0,\"CoordX\":41.173740386962891,\"CoordY\":-8.5474367141723633,\"Provider\":\"ST\",\"Lines\":null}],\"Direction\":\"R\"}]"

After I receive the response I do the following:

let dict = try! JSONSerialization.jsonObject(data: responseData!, options: .allowFragments) as? [[String:Any]] ?? [[String:Any]]()

Which results in the following dictionary (I'm sorry for the picture, but I could not take a print screen. Plus those 44 elements are the total number of Places, but I've simplified the response string as I said above)

My problem is, I cannot access each Place dictionary. I've tried iterating through dict["Places"] but that does not seem to work, which I do not understand, given it is an NSArray.

I may be missing something simple, but I can't seem to figure it out.

Any help is welcome.

Thanks!


Solution

  • You can try

    // MARK: - Root
    struct Root: Codable {
        let co2: Int
        let places: [Place]
        let direction: String
    
        enum CodingKeys: String, CodingKey {
            case co2 = "CO2"
            case places = "Places"
            case direction = "Direction"
        }
    }
    
    // MARK: - Place
    struct Place: Codable {
        let name, code: String
        let type: Int
        let coordX, coordY: Double
        let provider: String
        let lines: String?
    
        enum CodingKeys: String, CodingKey {
            case name = "Name"
            case code = "Code"
            case type = "Type"
            case coordX = "CoordX"
            case coordY = "CoordY"
            case provider = "Provider"
            case lines = "Lines"
        }
    }
    

    let res = try JSONDecoder().decode([Root].self,from:data)
    print(res.places)