2017-10-06 157 views
-1

我們有一個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 
} 
} 

問題是正確映射它創建的對象,這將是實現這一目標的最佳方式是什麼?

+0

https://www.raywenderlich.com/ 150322/swift-json-tutorial-2或https://developer.apple.com/swift/blog/?id=37 – CodeNinja

+0

我認爲你應該把標題和正文放在名爲'alert'或'detailType'的模型中(I thi nk您正在使用'detailType',順便說一句,您應該用大寫字母來命名類型,例如DetailType) – 3stud1ant3

+1

您實際上在映射時遇到了什麼問題?你的問題顯示沒有試圖做任何映射到解析JSON的任何嘗試。 – rmaddy

回答

1

您應該使用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 
    } 
} 
0

您可以在您的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) 

} 

希望有所幫助。