我已经解码了我的JSON Api,所以我可以在contentView中显示它,但我得到了这个错误
valueNotFound(Swift.String,Swift.DecodingError.Context(codingPath:[_JSONKey(字符串值:"索引1",intValue:1(,CodingKeys(字符串值:"DEALER_PICTURE",intValue:nil(],debugDescription:";应为String值,但发现为null&";,underlyingError: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?