UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Fetching data from JSON and decoding it.

Forums > Swift

Hey guys!

I have some issues with fetching data from JSON.

I've created an object of type Item, this is how it looks.

struct Item: Codable, Identifiable {
    var id = UUID()
    var products: Product
}

struct Product: Codable {
    let barcodeNumber:     String      // barcode_number
    var productName:        String?     // product_name
    var category:                 String?     // category
    var brand:                      String?     // brand
    var images:                   [String]?   // images
}

This is how the object looks like:

{ "products": [ { "barcode_number": "0140157379", "barcode_type": "ISBN", "barcode_formats": "ISBN 0140157379, ISBN 9780140157376", "mpn": "11712838", "model": "", "asin": "", "product_name": "Haroun and the Sea of Stories", "title": "Haroun and the Sea of Stories", "category": "Media > Books > Print Books", "manufacturer": "Penguin Books, Inc.", "brand": "Penguin Books", "label": "", "author": "Rushdie, Salman", "publisher": "Penguin Books", "artist": "", "actor": "", "director": "", "studio": "", "genre": "", "audience_rating": "Adult", "ingredients": "", "nutrition_facts": "", "color": "", "format": "Marketplace", "package_quantity": "", "size": "", "length": "", "width": "", "height": "", "weight": "0.4", "release_date": "", "description": "Excellent Marketplace listings for \"Haroun and the Sea of Stories\" by Salman Rushdie starting as low as $1.99!", "features": [], "images": [ "https://images.barcodelookup.com/134/1342375-1.jpg" ], "stores": [ { "store_name": "Textbooks.com", "store_price": "1.99", "product_url": "https://www.textbooks.com/Haroun-and-the-Sea-of-Stories-90-Edition/9780140157376/Salman-Rushdie.php&intsrc=CATF_2377", "currency_code": "USD", "currency_symbol": "$" }, { "store_nam

Object is quite long so I am uploading only the part of it here. But the data I am interested in, is in this part. During a catch where I decode data and put into the object, catch throws an error:

 do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let product = try decoder.decode([Item].self, from: data)
                print(product)
                completed(.success(product))

            } catch {
                completed(.failure(.chatchError))
            }

I can only assume that the error appears cause my custom object is not right. Do you have any suggestions what am I doing wrong?

Many thanks!

2      

What is the error?

2      

Hey!

typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

2      

var products: Product should be var products: [Product]

You will also run into issues with this:

"description": "Excellent Marketplace listings for \"Haroun and the Sea of Stories\" by Salman Rushdie starting as low as $1.99!"

because of the \

2      

Success! My object wasn't right. Json returned array of Product, not a single one. For those intrested in a solution:

import Foundation

struct Item: Codable {
//    var id = UUID()
    var products: [Product]
}

struct Product: Codable {
    let barcodeNumber:  String      // barcode_number
    var productName:    String?     // product_name
    var category:       String?     // category
    var brand:          String?     // brand
    var images:         [String]?   // images
}

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.