LoginSignup
2
1

More than 5 years have passed since last update.

APIKitのresponseメソッドの中でObjectMapperのクラスを正しくインスタンス化する

Last updated at Posted at 2017-03-21

事象

  • 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

もっとイケてる方法がありましたらこっそり教えてください :bow:

2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1