Home > database >  Decoding JSON from API with and adding products to an array from dictionary
Decoding JSON from API with and adding products to an array from dictionary

Time:10-17

I am a Swift beginner and I am trying to decode JSON objects from network request. I am trying to get the products into an array to use them later for the UI. Currently I am stuck on decoding the JSON and also having them placed in an array.

Here is the simplified version of the JSON i am trying to work with (but the full JSON can be found in the url):

{
  "items": [
    {
      "product": {
        "name": "Product name"
      }
    }
  ]
}

And here is the Swift code so far.

// Models
struct Root: Codable {
    let items: [Item]
}

struct Item: Codable {
    let product: Product
}

struct Product: Codable {
    let name: String
}

//Product array
var productArray: [Product] = []

// URL and data fetching
let urlString: String = "https://api.jsonbin.io/b/60832bec4465377a6bc6b6e6"

func fetchData() {
    
    guard let url = URL(string: urlString) else {
        return
    }
    
    let task = URLSession.shared.dataTask(with: url) { data, _, error in
        
        guard let data = data, error == nil else {
            return
        }
        
        do {
            let result = try JSONDecoder().decode(Root.self, from: data)
            
            DispatchQueue.main.async {
                productArray = result
            }
            
        } catch {
            print(error)
        }
    }
    
    task.resume()
}

fetchData()

If anyone knows how I can get past this, I greatly appreciate the help. Currently been stuck on this for a few hours, and I can't seem to figure it out. Thanks in advance!

CodePudding user response:

Just map the items array

DispatchQueue.main.async {
   productArray = result.items.map(\.product)
}
  • Related