JSON parsing in Swift 4 with complex & nested data

前端 未结 2 1485
深忆病人
深忆病人 2021-01-15 12:14

I am currently trying to make a weather app using JSON from https://openweathermap.org but I am having trouble with the weather part in the JSON file. I am not sure how to a

2条回答
  •  难免孤独
    2021-01-15 13:03

    You need to define types for the custom types in your JSON, e.g. weather, clouds, coord, etc. I would recommend looking at the example in the documentation.

    In the example, the Landmark type has a 'location' property which is of Coordinate type. You could even use the Coordinate type in the example for the coord property in your JSON object. However, you will need to provide the correct keys using the CodingKey protocol which is also described in the documentation. For example, your Coordinate type may look like this:

    struct Coordinate: Codable {
        var latitude: Double
        var longitude: Double
    
        enum CodingKeys: String, CodingKey {
            case latitude = "lat"
            case longitude = "lon"
        }
    }
    

提交回复
热议问题