0
1

More than 1 year has passed since last update.

AlamofireのresponeJsonでJSONを楽に扱う

Last updated at Posted at 2020-11-15

Alamofireには、JSONを返すAPIを扱うためのresponseJSONというメソッドがあるが、あまり使われていないので紹介。

responseJsonとは?

Apiから返却されたjsonを[Any : Any]のdictionaryへと格納するメソッド。
jsonを型にマッピングする必要がないため、かなり記述量が減る。

age: 90
というjsonが、

[ "age" : 90 ]

のようなdictionaryに格納される。
デメリットとしては、型情報が全てAnyで帰ってくるため、バリデーションは自前で実装する必要がある。

import Alamofire let url = "https://swapi.dev/api/people/1/" Alamofire . request ( url ) . responseJSON { response in if let json = response . result . value as? NSDictionary { print ( json ) // 以下が表示される。 // "name": "Luke Skywalker", // "height": "172", // "mass": "77", // "hair_color": "blond", // "skin_color": "fair", // "eye_color": "blue", // "birth_year": "19BBY", // "gender": "male", // ... print ( response . result )
スターウォーズApiから返却されるJSON
    "name": "Luke Skywalker",
    "height": "172",
    "mass": "77",
    "hair_color": "blond",
    "skin_color": "fair",
    "eye_color": "blue",
    "birth_year": "19BBY",
    "gender": "male",

情報を取り出したい場合は以下のように、通常のdictとして扱える。

json["name"] json["hair_corol"]

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
What you can do with signing up
1