简体   繁体   English

在swift4中将自定义对象数组转换为String

[英]Convert array of custom object to String in swift4

I am new to Swift and have an issue converting an array of custom object, to String. 我是Swift新手,在将自定义对象数组转换为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. 在webservice调用之后,我得到以下响应,它将被映射到Tickets类。 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? 现在,我可以将[Tickets]数组转换为String吗? If so, how? 如果是这样,怎么办? Also, how to get it back as [Tickets] from a class of String . 另外,如何从String类中以[Tickets]获取它。

I want to store it into UserDefaults after converting it to String, and retrieve it later 我想将其转换为String后将其存储到UserDefaults中,并在以后检索

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. 如果应该在init方法中初始化属性或成员,请不要将结构或类中的属性或成员声明为隐式未包装的可选属性。 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). 如果它们可能为nil则将它们声明为常规可选( ? ),否则声明为非可选(是的,如果没有问题或感叹号,编译器将不会抱怨)。

Just decode and encode the JSON with JSONDecoder() and JSONEncoder() 只需使用JSONDecoder()JSONEncoder()对JSON进行解码和编码

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM