事象
- APIKitの
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> SomeClass
関数の中でObjectMapperのクラスをインスタンス化する方法がわからない。 - ObjectMapperのクラスは
SomeClass(JSONString: jsonString)
というふうにインスタンス化する - その
jsonString
の引っ張り方がわからない
やってみたこと
- とりあえず
print(type(of: object))
する。 -
__NSDictionaryI
って出てきた - __NSDictionaryI json string とかでググったら ここ が出てきた。
-
どうやらJSONSerialization.data(withJSONObject: object, options: .prettyPrinted)
ってやるといけるらしい!- →普通に
[String: Any]
に直すだけでいけた(コメントより)
- →普通に
結果
(下記のものは非推奨です。 こちら を参照してください)
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> SomeClass {
let data = try JSONSerialization.data(withJSONObject: object, options: .prettyPrinted)
guard
let jsonString = String(data: data, encoding: .utf8),
let someInstance = SomeClass(JSONString: jsonString)
else { throw /* なんか例外 */ }
return someInstance
}
これで正しくObjectMapperのクラスからインスタンスを得られるはずです。 🐣
あわせて読みたい
pm11さんのこちらのエントリでは、 buildWithArray
という関数を使っていました。
http://qiita.com/pm11/items/57b2dff4b1ac19bd89ba
もっとイケてる方法がありましたらこっそり教えてください