Simple and clean way to convert JSON string to Object in Swift

前端 未结 16 1232
挽巷
挽巷 2020-11-28 23:27

I have been searching for days to convert a fairly simple JSON string to an object type in Swift but with no avail.

Here is the code for web service call:



        
16条回答
  •  野性不改
    2020-11-28 23:55

    For Swift 4, i wrote this extension using the Codable protocol:

    struct Business: Codable {
        var id: Int
        var name: String
    }
    
    extension String {
    
        func parse(to type: D.Type) -> D? where D: Decodable {
    
            let data: Data = self.data(using: .utf8)!
    
            let decoder = JSONDecoder()
    
            do {
                let _object = try decoder.decode(type, from: data)
                return _object
    
            } catch {
                return nil
            }
        }
    }
    
    var jsonString = "[\n" +
        "{\n" +
        "\"id\":72,\n" +
        "\"name\":\"Batata Cremosa\",\n" +
        "},\n" +
        "{\n" +
        "\"id\":183,\n" +
        "\"name\":\"Caldeirada de Peixes\",\n" +
        "},\n" +
        "{\n" +
        "\"id\":76,\n" +
        "\"name\":\"Batata com Cebola e Ervas\",\n" +
        "},\n" +
        "{\n" +
        "\"id\":56,\n" +
        "\"name\":\"Arroz de forma\",\n" +
    "}]"
    
    let businesses = jsonString.parse(to: [Business].self)
    

提交回复
热议问题