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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.