Santi Albus
Santi Albus

Reputation: 17

Trying to parse an json file with Swifty JSON

i'm practicing with Alamofire and SwiftyJSON in Swift, but I have a problem.

I'm trying to get an element in JSON that is in a diferent level, but it keeps me showing nil or null, or the fields it's empty.

Although I'm using the marvel developer app.

My Code:

Alamofire.request(urlGetCharaters).responseJSON { response in
        if let value = response.result.value {
            let json = JSON(value)

            print("Pa ti")
            print(json["data"]["results"]["name"].stringValue)

        }

It's keep me saying that is empty.

The Json is this:

"code": 200,
"status": "Ok",
"copyright": "© 2018 MARVEL",
"attributionText": "Data provided by Marvel. © 2018 MARVEL",
"attributionHTML": "<a href=\"http://marvel.com\">Data provided by Marvel. © 2018 MARVEL</a>",
"etag": " ",
"data": {
    "offset": 0,
    "limit": 20,
    "total": 1491,
    "count": 20,
    "results": [
        {
            "id": 1011334,
            "name": "3-D Man",
            "description": "",
            "modified": "2014-04-29T14:18:17-0400",
            "thumbnail": {
                "path": "http://i.annihil.us/u/prod/marvel/i/mg/c/e0/535fecbbb9784",
                "extension": "jpg"
            },

I'm trying to get in: data -> results and then get "name".

Any solution? Thanks

Upvotes: 0

Views: 352

Answers (1)

Ahmet Sina Ustem
Ahmet Sina Ustem

Reputation: 1090

As commented by rmaddy, you should get first result name like this:

print(json["data"]["results"][0]["name"].stringValue)

Don't forget array and object are different.

Upvotes: 3

Related Questions