Home > Mobile >  How to save names from json to list in swift
How to save names from json to list in swift

Time:06-02

I am trying to save all names from a json url to a list but it doesn’t work.

I am using this code:

let jsonUrl = ("https://de1.api.radio-browser.info/json/stations/byname/jazz")
Alamofire.request( jsonUrl).responseJSON { (responseData) -> Void in
    if((responseData.result.value) != nil) {
        
        let swiftyJsonVar = JSON(responseData.result.value!)
        
        for (_, subJson):(String, JSON) in swiftyJsonVar {
            
            for (_, subJson):(String, JSON) in subJson {
                
                let nameList = subJson["name"].stringValue
                print(nameList)
            }
        }
    }
}

What can I do to fix it?

CodePudding user response:

Using Codable structs makes this kind of tasks a lot easier.

Consider this:

//Create a struct that contains the values you are interested in
struct NameResponse: Codable{
    var name: String
}

let jsonUrl = ("https://de1.api.radio-browser.info/json/stations/byname/jazz")

    Alamofire.request( jsonUrl).responseData { (responseData) -> Void in
        if((responseData.result.value) != nil) {
            //Now decode the response data to an array of your structs
            let names = try! JSONDecoder().decode([NameResponse].self, from: responseData.result.value!)
            //Now you can map them to an array or process them anyway you want
            let nameArray = names.map{$0.name}
            print(nameArray)
        }
}

Edit:

If you need the data from an Alamofire response you would need to call the .responseData handler instead of the .responseJSON one.

  • Related