-1

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

Naren
  • 115
  • 2
  • 14
  • you could [`map(_:)`](https://developer.apple.com/documentation/swift/array/2908681-map) (or [`flatMap(_:)`](https://developer.apple.com/documentation/swift/array/2903427-flatmap)) a collection anytime at your convenience; that could work in any ways... isn't that good enough? – holex Feb 05 '18 at 16:34

1 Answers1

2

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)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • That's what I was looking for. Yes, I take your words in bold and do the changes in the struct. Thanks – Naren Feb 06 '18 at 08:16