I want to write dont let values
I have
"id": 17,
"name": "",
"team_id": 4,
"is_delete": false,
"created_at": "2018-04-30",
"members": [
{
"id": 42,
"username": "ie",
}
],
"description": null,
Im try to do this
let id: Int
let name: String
let team_id: Int
let is_delete: Bool
let created_at: String
let description: NSNull
but dont know hove correctly add the members array . and NSNull is correct to null value?
So I suppose you are trying to write a Codable
struct/class that can be used to decode your JSON?
The way to handle null
is to use optional types. From the name, I guess description
would have been a string if it were not null, so we should use String?
as the type:
struct TeamMember: Codable {
let id: Int
let username: String
}
struct Team: Codable {
let id: Int
let name: String
let team_id: Int
let is_delete: Bool
let created_at: String
let members: [TeamMember]
let description: String? // <---- this line
}
Here is an example of decoding:
// I escaped the json using an online decoder I found. It's basically the same JSON in the question.
let jsonData = "{ \"id\": 17,\r\n \"name\": \"\",\r\n \"team_id\": 4,\r\n \"is_delete\": false,\r\n \"created_at\": \"2018-04-30\",\r\n \"members\": [\r\n {\r\n \"id\": 42,\r\n \"username\": \"ie\",\r\n }\r\n ],\r\n \"description\": null}".data(using: .utf8)
let decoder = JSONDecoder()
let team = try! decoder.decode(Team.self, from: jsonData!)
print(team.id)