【问题标题】:How to handle JSON with null values using Decodable如何使用 Decodable 处理具有空值的 JSON
【发布时间】:2021-06-26 07:28:39
【问题描述】:

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

valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "索引 1", intValue: 1), CodingKeys(stringValue: "DEALER_PICTURE", intValue: nil)], debugDescription: "预期的字符串值,但发现为空。", 基础错误:无))

我意识到,我的 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()
}

【问题讨论】:

    标签: ios json swift decodable


    【解决方案1】:

    让它成为可选的

    var DEALER_PICTURE: String?
    

    【讨论】:

    • 现在我收到了这个错误Fatal error: Unexpectedly found nil while unwrapping an Optional value: file Test10/ContentView.swift, line 25 2021-03-30 16:36:43.126236+0700 Test10[4930:349342] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file Test10/ContentView.swift, line 25 (lldb)
    • Text(locations[index].DEALER_PICTURE)更改为Text(locations[index].DEALER_PICTURE ?? "Empty")
    猜你喜欢
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    相关资源
    最近更新 更多