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

前端 未结 16 1177
挽巷
挽巷 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-29 00:01

    SWIFT4 - Easy and elegant way of decoding JSON strings to Struct.

    First step - encode String to Data with .utf8 encoding.

    Than decode your Data to YourDataStruct.

    struct YourDataStruct: Codable {
    
    let type, id: String
    
    init(_ json: String, using encoding: String.Encoding = .utf8) throws {
        guard let data = json.data(using: encoding) else {
            throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
        }
        try self.init(data: data)
    }
    
    init(data: Data) throws {
        self = try JSONDecoder().decode(YourDataStruct.self, from: data)
    }                                                                      
    }
    
    do { let successResponse = try WSDeleteDialogsResponse(response) }
    } catch {}
    

提交回复
热议问题