-1

我们有一个 json 有效载荷:

{
  "aps": {
    "alert": {
      "title": "Payload",
      "body": "Lets map this thing"
    },
  },
  "type": "alert",
  "message": "This is a message",
}

自定义对象已创建:

class PushNotificationDetail {

var title: String //operation
var body: String //message
var type: detailType
var message: String?

init(title: String, body: String, type: detailType, message: string?){

    self.title = title
    self.body = body
    self.type = type
    self.message = message
}
}

问题是将其正确映射到创建的对象,实现这一目标的最佳方法是什么?

4

2 回答 2

3

您应该使用 Swift4 Codable 协议从 api 返回的 json 初始化您的对象。您需要重新构建结构以匹配 api 返回的数据:

struct PushNotificationDetail: Codable, CustomStringConvertible  {
    let aps: Aps
    let type: String
    let message: String?
    var description: String { return aps.description + " - Type: " + type + " - Message: " + (message ?? "") }
}
struct Aps: Codable, CustomStringConvertible {
    let alert: Alert
    var description: String { return alert.description }
}
struct Alert: Codable, CustomStringConvertible {
    let title: String
    let body: String
    var description: String { return "Tile: " + title + " - " + "Body: " + body }
}

extension Data {
    var string: String { return String(data: self, encoding: .utf8) ?? "" }
}

游乐场测试

let json = """
{"aps":{"alert":{"title":"Payload","body":"Lets map this thing"}},"type":"alert","message":"This is a message"}
"""

if let pnd = try? JSONDecoder().decode(PushNotificationDetail.self, from:  Data(json.utf8)) {
    print(pnd)  // "Tile: Payload - Body: Lets map this thing - Type: alert - Message: This is a message\n"
    // lets encode it
    if let data = try? JSONEncoder().encode(pnd) {
        print(data.string)  // "{"aps":{"alert":{"title":"Payload","body":"Lets map this thing"}},"type":"alert","message":"This is a message"}\n"
        print(data == Data(json.utf8))  // true
    }
}
于 2017-10-06T17:03:48.850 回答
0

您可以使用 PushNotificationDetail 类中的可失败初始化程序和链式保护语句来执行此操作:

init?(jsonDict: [String : Any]) {

    guard let typeString : String = jsonDict[“type”] as? String,
        let message: String = jsonDict[“message”] as? String,
        let aps : [String : Any] = jsonDict[“aps”] as? [String : Any],
        let alert : [String : String] = aps[“alert”] as? [String : String],
        let title : String = alert[“title”],
        let body : String = alert[“body”] else { return nil }

    // implement some code here to create type from typeString 

    self.init(title: title, body: body, type: type, message: message)

}

希望有帮助。

于 2017-10-06T16:27:05.830 回答