“The data couldn’t be read because it is missing” error when decoding JSON in Swift

后端 未结 5 569
温柔的废话
温柔的废话 2021-01-31 07:20

I am getting the following error :

The data couldn’t be read because it is missing.

When I run the following code:

struct Indicator: Decodable {
         


        
5条回答
  •  既然无缘
    2021-01-31 08:02

    Printing error.localizedDescription is misleading because it displays only a quite meaningless generic error message.

    So never use localizedDescription in Decodable catch blocks.

    In the simple form just

    print(error)
    

    It shows the full error including the crucial information debugDescription and context.Decodable errors are very comprehensive.


    While developing code you could catch each Decodable error separately for example

    } catch let DecodingError.dataCorrupted(context) {
        print(context)
    } catch let DecodingError.keyNotFound(key, context) {
        print("Key '\(key)' not found:", context.debugDescription)
        print("codingPath:", context.codingPath)
    } catch let DecodingError.valueNotFound(value, context) {
        print("Value '\(value)' not found:", context.debugDescription)
        print("codingPath:", context.codingPath)
    } catch let DecodingError.typeMismatch(type, context)  {
        print("Type '\(type)' mismatch:", context.debugDescription)
        print("codingPath:", context.codingPath)
    } catch {
        print("error: ", error)
    }
    

    It shows only the most significant information.

提交回复
热议问题