如何使用Swift 4解码以下json?
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 }这给了我以下错误:
keyNotFound(LocalNotificationsAlert.Root.CodingKeys.id, Swift.DecodingError.Context(codingPath:[],debugDescription:否 与键ID(\"id \").相关联的值.,底层错误:nil))
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.
推荐答案Root 对象不是具有id,packageId和package键的字典,即Root对象是具有键data,error,message的外部词典.
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.
所以您需要3个结构
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 }更多推荐
如何在Swift 4中解码JSON?
发布评论