I have a problem with JSON decoding. I have UpdateNickname and UpdateNicknameMessage structs and variable Message inside UpdateNickname could be a null. I got an error whenever it is a null. I want to handle this problem. Here is my struct:
struct UpdateNicknameMessage: Codable {
let id: Int
let nickname: String
let email: String
}
struct UpdateNickname: Codable {
var Status: Int
var Result: String
var Message: UpdateNicknameMessage
enum CodingKeys: String, CodingKey {
case Status = "Status"
case Result = "Result"
case Message = "Message"
}
init?(from jsonObject: AnyObject) {
guard let Status1: Int = jsonObject.object(forKey: "Status") as? Int,
let Result1: String = jsonObject.object(forKey: "Result") as? String,
let Message1: UpdateNicknameMessage = jsonObject.object(forKey: "Message") as? UpdateNicknameMessage
else { return nil }
Status = Status1
Result = Result1
Message = Message1
}
}
and JSON looks like this:
{"Message": {
email = "[email protected]";
id = 56;
nickname = testNickname;
},
"Status": 200,
"Result": success}
And this is my code for decoding JSON in swift. I use try catch to handle my error.
let decoder = JSONDecoder()
do {
let model = try decoder.decode(UpdateNickname.self, from: data)
let serverStatus = model.Status
if serverStatus == 200 {
//EVERYTHING IS FINE
} else {
//server not working
}
} catch {
//cant convert JSON into struct
print(error.localizedDescription)
}
so my variable Message can return null if something goes wrong with the server.
{"Message": null,
"Status": 400,
"Result": problem}
When i try to decode JSON when Message is null i get an error
The data couldn’t be read because it is missing.
How can i fix this problem and handle null value?
JSONformat is invalidJSONas the following: ``` { "Message": { "email": "[email protected]", "id": 56, "nickname": "testNickname" }, "Status": 200, "Result": "success" } ```<null>!=null