0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have 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が、

```swift

["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"]
0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?