问题
How to decode following json using Swift 4?
{
"data": {
"id": 22,
"packageId": 5,
"Package": {
"id": 5,
"color": "blue"
}
},
"error": false,
"message": "Successfully Fetched"
}
I have tried it using following:
struct Root: Codable {
enum CodingKeys: String, CodingKey {
case id = "id"
case packageId = "packageId"
case package = "Package"
}
var package : Package
var id : Int
var packageId : Int
}
struct Package : Codable {
var id : Int
var color : String
}
It is giving me following error:
keyNotFound(LocalNotificationsAlert.Root.CodingKeys.id, Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key id (\"id\").", underlyingError: nil))
Please help me in fixing this, Thank you.
回答1:
The Root object is not the dictionary with id
, packageId
and package
keys, the Root
object is the outer dictionary with keys data
, error
, message
.
So you need 3 structs
struct Root: Codable {
let data : PackageData? // If `error` is true `data` might be missing
let error : Bool
let message : String
}
struct PackageData: Codable {
enum CodingKeys: String, CodingKey {
case package = "Package"
case id, packageId
}
let package : Package
let id : Int
let packageId : Int
}
struct Package : Codable {
let id : Int
let color : String
}
回答2:
If you don't want to custom decode the response, you would need to provide the struct for the entire json response.
struct Response: Decodable {
let data: Root
let error: Bool
let message: String
}
来源:https://stackoverflow.com/questions/48161748/how-to-decode-json-in-swift-4