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

SOLVED: error decoding

Forums > SwiftUI

My struct:

struct Produtos : Identifiable, Codable{
    var id = UUID()
    var produto : String
    var descricao : String
    var imagem : [String]
    var preco : Double
    var destaque : Bool
    var categoria : String
    var ordenacao : Int
    var lojaID : Int

    enum CodingKeys: String, CodingKey {
        case produto, descricao, imagem, preco, destaque, categoria, ordenacao, lojaID
    }

}

My Json File: ` [

    {
        "produto": "Suco de Uva Orgânico 1L",
        "descricao": "Características: A uva utilizada na elaboração do produto é cultivada no sistema orgânico. Sem adição de agrotóxicos, o que induz a autodefesa da planta. Este produto é 100% natural, não é elaborado a partir de suco concentrado, não contém água, corantes ou conservantes.  Certificações: - ISO 22.000, garantindo um produto seguro da videira até a mesa. - SUCO DE UVA PURO, que garant",
        "imagem:": ["myimageurl"],
        "preco": 27.39,
        "destaque": true,
        "categoria": "Bebidas",
        "ordenacao": 1,
        "lojaID": 1
    }
]`

Whats my error "Failed to decode produtos.json from bundle."

3      

Your struct doesn't match your JSON.

Your JSON has a key "imagem:" (with a colon :) but your struct has imagem (with no colon). Either remove the colon from the JSON key or use case imagem = "imagem:" in your CodingKeys enum.

A tip: If you want better error information, don't decode your JSON using try?. That swallows the error by turning it into an optional. Use a do {} catch {} block instead and examine the error that is caught.

3      

Hi when using JSON I tend to use Ducky - Model Editor and when paste JSON file in you get

struct Produto: Decodable {
  let produto: String
  let descricao: String
  let imagem: [String]
  let preco: Double
  let destaque: Bool
  let categoria: String
  let ordenacao: Int
  let lojaID: Int

  private enum CodingKeys: String, CodingKey {
    case produto
    case descricao
    case imagem = "imagem:"
    case preco
    case destaque
    case categoria
    case ordenacao
    case lojaID
  }
}

However as @roosterboy suggest and remove the : from imagem you get this. (no need for CodingKeys)

struct Produto: Decodable {
  let produto: String
  let descricao: String
  let imagem: [String]
  let preco: Double
  let destaque: Bool
  let categoria: String
  let ordenacao: Int
  let lojaID: Int
}

If you want to make it Identifiable then you can not add var id = UUID() best to change to

var id: Int { lojaID }

assuming that lojaID is unique!

One other note that you have the main struct as Produto and a property called produto. As this might be a bit confusing in call sites as general when refering to a single of the array you would use produto

struct ContentView: View {
    let produtos = Bundle.main.decode([Produto].self, from: "MyFile.json")

    var body: some View {
        List {
            ForEach(produtos) { produto in
                VStack {
                    Text(produto.produto) //<- produto and produto!
                        .font(.largeTitle)
                    Text(produto.descricao)
                        .foregroundColor(.secondary)
                }
            }
        }
    }
}

3      

Thankyou my friens Work fine!

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.