如何将JSON有效载荷转换为自定义对象?
问题描述:
我们有一个JSON有效载荷:如何将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
}
}
问题是正确映射它创建的对象,这将是实现这一目标的最佳方式是什么?
答
您应该使用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
}
}
答
您可以在您的PushNotificationDetail类failable初始化剂和链警卫声明这样做:
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)
}
希望有所帮助。
https://www.raywenderlich.com/ 150322/swift-json-tutorial-2或https://developer.apple.com/swift/blog/?id=37 – CodeNinja
我认为你应该把标题和正文放在名为'alert'或'detailType'的模型中(I thi nk您正在使用'detailType',顺便说一句,您应该用大写字母来命名类型,例如DetailType) – 3stud1ant3
您实际上在映射时遇到了什么问题?你的问题显示没有试图做任何映射到解析JSON的任何尝试。 – rmaddy