![]() | 新品価格 |

swiftで新規APIからデータを取得するに必要があり
新しいパーサーを作るよりもmapperのOSSを使う方が良いなぁと思い
調べてみたら、出てきたのがObjectMapper
https://github.com/Hearst-DD/ObjectMapper
そんなわけで、こいつを使ってみた
・ObjectMapperを使う側
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
let dummy = Mapper<A>().map(JSONObject: json)
} catch {
print(error)
}
・モデル1
import Foundation
import ObjectMapper
class A: Mappable {
var C: [Model2]
required init?(map: Map) {
C = []
}
func mapping(map: Map) {
C <- map["result.data"]
}
}
・モデル2
import Foundation
import ObjectMapper
class Model2: Mappable {
var title: String?
required init?(map: Map) {
}
func mapping(map: Map) {
title <- map["title"]
}
}
・ただし
swift4でCodableができると不要になる模様
なのでこのタイミングだと待った方が良さそうです
https://github.com/Hearst-DD/ObjectMapper/issues/823
タグ:Swift