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

后端 未结 5 572
温柔的废话
温柔的废话 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:01

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

    the error coming from this code:

    ...catch {
        print(error.localizedDescription)
    }
    

    Because: seems that a key is missing or mistyped.

    You can check which key is missing by coding like this:

    ...catch {
        debugPrint(error)
    }
    

    Note: If struct keys are different from JSON data keys, see below example: the key in struct is 'title' but in data is 'name'.

    struct Photo: Codable {
        var title: String
        var size: Size
    
        enum CodingKeys: String, CodingKey
        {
            case title = "name"
            case size
        }
    }
    

    If you mistype 'name', the error will pop up.

    Also, if you mistype this 'CodingKeys', you will get the error.

    enum CodingKeys:...
    

提交回复
热议问题