Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Codable decode empty json as nil or empty object

Here's my code:

class LoginUserResponse : Codable {
    var result: String = ""
    var data: LoginUserResponseData?
    var mess: [String] = []
}

public class LoginUserResponseData : Codable {
    var userId = "0"
    var name = ""
}

Now, calling the server API I'm parsing response like this (using Stuff library to simplify parsing):

do {
    let loginUserResponse = try LoginUserResponse(json: string)
} catch let error {
    print(error)
}

When I enter the correct password I'm getting an answer like this:

{"result":"success","data":{"userId":"10","name":"Foo"},"mess":["You're logged in"]}

This is fine, the parser is working correctly.

While providing wrong password gives the following answer:

{"result":"error","data":{},"mess":["Wrong password"]}

In this situation, the parser is failing. It should set data to nil, but instead, it tries to decode it to the LoginUserResponseData object.

I'm using the same approach on Android using retrofit and it works fine. I rather don't want to make all fields as optional.

Is there a way to make parser treat empty json {} as nil? Or make LoginUserResponseData as non-optional and it'll just have default values? I know I can create a custom parser for this, but I have tons of requests like this and it'll require too much additional work.

like image 868
Makalele Avatar asked Feb 23 '18 07:02

Makalele


3 Answers

As easy as that !

class LoginUserResponse : Codable {
    var result: String = ""
    var data: LoginUserResponseData?
    var mess: [String] = []

    private enum CodingKeys: String, CodingKey {
        case result, data, mess
    }

    required init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        result = try values.decode(String.self, forKey: .result)
        mess = try values.decode([String].self, forKey: .mess)
        data = try? values.decode(LoginUserResponseData.self, forKey: .data)
    }
}

public class LoginUserResponseData : Codable {
    var userId = "0"
    var name = ""
}

let str = "{\"result\":\"success\",\"data\":{\"userId\":\"10\",\"name\":\"Foo\"},\"mess\":[\"You're logged in\"]}"
let str2 = "{\"result\":\"error\",\"data\":{},\"mess\":[\"Wrong password\"]}"

let decoder = JSONDecoder()
let result = try? decoder.decode(LoginUserResponse.self, from: str.data(using: .utf8)!)
let result2 = try? decoder.decode(LoginUserResponse.self, from: str2.data(using: .utf8)!)
dump(result)
dump(result2)
like image 63
Arsonik Avatar answered Oct 26 '22 23:10

Arsonik


This is what your implementation of init(from: Decoder) should look like.

Note: You should consider changing LoginUserResponse from a class to a struct, since all it does is store values.

struct LoginUserResponse: Codable {
    var result: String
    var data: LoginUserResponseData?
    var mess: [String]

    init(from decoder: Decoder) throws
    {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        result = try values.decode(String.self, forKey: .result)
        mess = try values.decode([String].self, forKey: .mess)
        if let d = try? values.decode(LoginUserResponseData.self, forKey: .data) {
            data = d
        }
    }
}
like image 37
Sam Avatar answered Oct 27 '22 00:10

Sam


My recommendation is to decode result as enum and to initialize data on success.

struct LoginUserResponse : Decodable {

    enum Status : String, Decodable { case success, error }
    private enum CodingKeys: String, CodingKey { case result, data, mess }

    let result : Status
    let data : UserData?
    let mess : [String]

    init(from decoder: Decoder) throws
    {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        result = try values.decode(Status.self, forKey: .result)
        mess = try values.decode([String].self, forKey: .mess)
        switch result {
            case .success: data = try values.decode(UserData.self, forKey: .data)
            case .error: data = nil
        }
    }
}

public struct UserData : Decodable {
    let userId : String
    let name : String
}
like image 44
vadian Avatar answered Oct 27 '22 01:10

vadian