如何在Swift 4中解码JSON?

编程入门 行业动态 更新时间:2024-10-03 14:29:37
本文介绍了如何在Swift 4中解码JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使用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?

本文发布于:2023-11-26 09:47:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633620.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Swift   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!