I am new to Swift and have an issue converting an array of custom object, to String.
This is my response class Tickets
public struct Tickets: Codable {
public let name: String!
public let status: String!
public let department: String!
}
After the webservice call i get following response and it would be mapped to Tickets class. Now, I have an array of "Tickets" as [Tickets] described below.
"tickets": [
{
"name": "d5b5d618-8a74-4e5f",
"status": "VALID",
"department": "IT"
},
{
"name": "a58f54b5-9420-49b6",
"status": "INVALID",
"department": "Travel"
}
]
Now, can I convert an array of [Tickets]
to String? If so, how? Also, how to get it back as [Tickets]
from a class of String
.
I want to store it into UserDefaults after converting it to String, and retrieve it later
First of all:
Never declare properties or members in a struct or class as implicit unwrapped optional if they are supposed to be initialized in an init
method. If they could be nil
declare them as regular optional (?
) otherwise as non-optional (Yes, the compiler won't complain if there is no question or exclamation mark).
Just decode and encode the JSON with JSONDecoder()
and JSONEncoder()
let jsonTickets = """
{"tickets":[{"name":"d5b5d618-8a74-4e5f","status":"VALID","department":"IT"},{"name":"a58f54b5-9420-49b6","status":"INVALID","department":"Travel"}]}
"""
public struct Ticket: Codable {
public let name: String
public let status: String
public let department: String
}
do {
let data = Data(jsonTickets.utf8)
let tickets = try JSONDecoder().decode([String:[Ticket]].self, from: data)
print(tickets)
let jsonTicketsEncodeBack = try JSONEncoder().encode(tickets)
jsonTickets == String(data: jsonTicketsEncodeBack, encoding: .utf8) // true
} catch {
print(error)
}