"Data cannot be read because it is missing" when decoding JSON in Swift

I get the following error:

Data cannot be read because it is missing.

When I run the following code:

struct Indicator: Decodable {
    let section: String
    let key: Int
    let indicator: Int
    let threshold: Int
}
    var indicators = [Indicator]()

    do {
        if let file = Bundle.main.url(forResource: "indicators", withExtension: "json") {
            indicators = try JSONDecoder().decode([Indicator].self, from: try Data(contentsOf: file))
        }
    } catch {
        print(error.localizedDescription)
    }

They are in function, but I deleted them for clarity. I have a block of code that is very similar in another file (I copied this code and changed the names substantially), so I'm not sure why this is happening. The json file is valid json and the target is configured correctly.

thank

+16
source share
4 answers

I just solved a similar problem at my end, but for a property list decoder.

An error in this case means that the key was not found, and not the data as a whole.

, nil, .

+26

, . "No value associated with key someKey (\"actual_key_if_you_defined_your_own\").", , localizedDescription.

+22

error.localizedDescription , .

localizedDescription Decodable .

print(error)

, debugDescription context. Decodable .


Decodable ,

} 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)
}

.

+16

" , "

, :

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

: , .

, , :

...catch {
    debugPrint(error)
}

. JSON, . : - "", - "".

struct Photo: Codable {
    var title: String
    var size: Size

    enum CodingKeys: String, CodingKey
    {
        case title = "name"
        case size
    }
}

"", .

, "CodingKeys", .

enum CodingKeys:...
0

Source: https://habr.com/ru/post/1688234/


All Articles