如何使用 Decodable

问题描述

我已经解码了我的 JSON Api,所以我可以在我的 contentView 中显示它,但是我遇到了这个错误

valueNotFound(Swift.String,Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1",intValue: 1),CodingKeys(stringValue: "DEALER_PICTURE",intValue: nil)],debugDescription: "预期的字符串值,但发现为 null。",底层错误:nil))

我意识到,我的 JSON 中有一个空值

  "id":8,"DEALER_NAME":"Bluejam","DEALER_ADDRESS":"85703 Westridge Trail","DEALER_PICTURE":null

如何在不更改 JSON 值的情况下修复此错误? 这是我的代码

import SwiftUI

struct ContentView: View {
    @State var locations: [ServiceLocationjsON] = []
    var body: some View {
        vstack{
            if locations.isEmpty{
                vstack{
                    Spacer()
                    ProgressView()
                    Spacer()
                }
            }else{
                vstack{
                    ScrollView{
                        ForEach(0..<locations.count){ index in
                            vstack(spacing: 10){
                                Text(locations[index].DEALER_PICTURE)
                            }
                        }
                    }
                }
            }
        }.onAppear{
            getLocationData(url: "https://my.api.mockaroo.com/null_value.json?key=e57d0e40"){
                (locations) in
                self.locations = locations
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    
    static var previews: some View {
        ContentView()
    }
}

struct ServiceLocationjsON: Identifiable,Decodable{
    var id: Int
    var DEALER_NAME: String
    var DEALER_PICTURE: String
}

func getLocationData(url: String,completion: @escaping ([ServiceLocationjsON])->()){
    let session = URLSession(configuration: .default)
    session.dataTask(with: URL(string: url)!){ (data,_,err) in
        if err != nil{
            print(err!.localizedDescription)
            return
        }
        do{
            let locations = try
                JSONDecoder().decode([ServiceLocationjsON].self,from: data!)
            completion(locations)
        }
        catch{
            print(error)
        }
    }.resume()
}

解决方法

使其成为可选

var DEALER_PICTURE: String?