When parsing you will be turning the results into a dictionary of objects.
To see how to get the JSON see this post.
Example JSON
To get data out of this dictionary you do something like this:
(Swift 2.2)
To see how to get the JSON see this post.
Example JSON
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "http://swapi.co/api/planets/1/",
"films": [
"http://swapi.co/api/films/6/",
"http://swapi.co/api/films/3/",
"http://swapi.co/api/films/2/",
"http://swapi.co/api/films/1/",
"http://swapi.co/api/films/7/"
],
"species": [
"http://swapi.co/api/species/1/"
],
"vehicles": [
"http://swapi.co/api/vehicles/14/",
"http://swapi.co/api/vehicles/30/"
],
"starships": [
"http://swapi.co/api/starships/12/",
"http://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "http://swapi.co/api/people/1/"
}
Then you convert it into a dictionary:
let dict = json as! Dictionary<String, AnyObject>So you are really dividing up the JSON like this:
| Key | Value | ||
| String | AnyObject | ||
| { | |||
| "name": | "Luke Skywalker", | String | |
| "height": | "172", | String | |
| "mass": | "77", | String | |
| "hair_color": | "blond", | String | |
| "skin_color": | "fair", | String | |
| "eye_color": | "blue", | String | |
| "birth_year": | "19BBY", | String | |
| "gender": | "male", | String | |
| "homeworld": | "http://swapi.co/api/planets/1/", | String | |
| "films": | [ | Array<String> | |
| "http://swapi.co/api/films/6/", | |||
| "http://swapi.co/api/films/3/", | |||
| "http://swapi.co/api/films/2/", | |||
| "http://swapi.co/api/films/1/", | |||
| "http://swapi.co/api/films/7/" | |||
| ], | |||
| "species": | [ | Array<String> | |
| "http://swapi.co/api/species/1/" | |||
| ], | |||
| "vehicles": | [ | Array<String> | |
| "http://swapi.co/api/vehicles/14/", | |||
| "http://swapi.co/api/vehicles/30/" | |||
| ], | |||
| "starships": | [ | Array<String> | |
| "http://swapi.co/api/starships/12/", | |||
| "http://swapi.co/api/starships/22/" | |||
| ], | |||
| "created": | "2014-12-09T13:50:51.644000Z", | String | |
| "edited": | "2014-12-20T21:17:56.891000Z", | String | |
| "url": | "http://swapi.co/api/people/1/" | String | |
| } | |||
To get data out of this dictionary you do something like this:
let dict = json as! Dictionary<String, AnyObject> let name = dict["name"] let height = dict["height"] let films: Array = dict["films"] as! Array<String> let film1 = films[0]
(Swift 2.2)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.