Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将json负载转换为自定义对象?_Json_Swift_Push Notification_Payload_Codable - Fatal编程技术网

如何将json负载转换为自定义对象?

如何将json负载转换为自定义对象?,json,swift,push-notification,payload,codable,Json,Swift,Push Notification,Payload,Codable,我们有一个json负载: { "aps": { "alert": { "title": "Payload", "body": "Lets map this thing" }, }, "type": "alert", "message": "This is a message", } 已创建自定义对象: class PushNotificationDetail { var title: String //operation var bod

我们有一个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
}
}

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

您可以使用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)

}

希望这会有所帮助。

您应该使用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 }
}


操场测试

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

或者我认为您应该将标题和正文放在名为
alert
detailType
的模型中(我认为您使用的是
detailType
,顺便说一句,您应该用大写字母命名您的类型,例如detailType)您在映射方面实际遇到了什么问题?您的问题表明,没有人试图将任何映射到任何解析JSON的尝试。此处已充分讨论:
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
    }
}