VolumeMax
VolumeMax

Reputation: 11

How to parse this json with alamofire

How to parse this json in my code? What data model to collect?. I don’t understand how to cast dictionaries in dictionaries later.

I get an error opposite let artist:

Value of type 'Dictionary<String, [String : AnyObject]>.Element' (aka '(key: String, value: Dictionary<String, AnyObject>)') has no subscripts

func fetchCurrentChartsWithAlamofire(apiMethod: String) {
        
        let url = "https://"
        
        request(url).validate().responseJSON { responseData in
            
            switch responseData.result {
            case .success(let value):
                
                guard let jsonData = value as? [String:[String:AnyObject]] else { return }
                
                for artists in jsonData {
                    let artist = Artist(name: artists["artists"])
                }
                
                
            case .failure(let error):
                print(error)
            }
        }
    }

Here is json in the browser:

{
"artists": {

"artist": [

{
"name": "The Weeknd",

}
]
}
}

Upvotes: 0

Views: 70

Answers (1)

Jawad Ali
Jawad Ali

Reputation: 14397

Here is how you can parse this

struct Artist:Decodable {
  let artists:Artists
}
struct Artists:Decodable {
  let artist: [ArtistName]
}

struct ArtistName:Decodable {
  let name: String
}

For json

enter image description here

Upvotes: 1

Related Questions