[SWIFT] Handle JSON effortlessly with Alamofire's respone Json

Alamofire has a method called responseJSON for handling API that returns JSON, but I will introduce it because it is not used much.

What is responseJson?

A method to store the json returned from Api in the dictionary of [Any: Any]. Since there is no need to map json to type, the amount of description is considerably reduced.

For example `` { age: 90 }

Json,

```swift

["age": 90]

It is stored in a dictionary like. The disadvantage is that all the type information is returned in Any, so you need to implement the validation yourself.


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)
 // The following is displayed.
        // {
	        // "name": "Luke Skywalker",
    	    // "height": "172",
	        // "mass": "77",
	        // "hair_color": "blond",
	        // "skin_color": "fair",
	        // "eye_color": "blue",
	        // "birth_year": "19BBY",
	        // "gender": "male",
            // ...
        // }
    }
    print(response.result)
}
 JSON returned from Star Wars API
{
	"name": "Luke Skywalker",
	"height": "172",
	"mass": "77",
	"hair_color": "blond",
	"skin_color": "fair",
	"eye_color": "blue",
	"birth_year": "19BBY",
	"gender": "male",
    ...
}

If you want to retrieve the information, you can handle it as a normal dict as follows.


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

Recommended Posts

Handle JSON effortlessly with Alamofire's respone Json
Handle JSON with minimal-json
Handle JSON in cross domain with Play Framework
Import JSON with SolrJ
JSON validation with JSON schema
Handle devise with Rails
Format JSON with org.json
[Java] JSON communication with jackson
Handle dates with Javascript (moment.js)