-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

1
  • you could map(_:) (or flatMap(_:)) a collection anytime at your convenience; that could work in any ways... isn't that good enough? Commented Feb 5, 2018 at 16:34

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's what I was looking for. Yes, I take your words in bold and do the changes in the struct. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.