swift - Codable: decoding by key
问题描述
Suppose I have an API that returns this json:
{
"dogs": [{"name": "Bella"}, {"name": "Lucy"}],
"cats": [{"name": "Oscar"}, {"name": "Coco"}]
}
And a model that looks like this:
import Foundation
public struct Animal: Codable {
let name: String?
}
Now I want to decode the array of Animal from the "dogs" key:
let animals = try JSONDecoder().decode([Animal].self, from: response.data!)
However, I somehow have to reference the "dogs" key. How do I do this?
解决方案
First of all, the JSON you provided is not valid JSON. So let's assume that what you actually mean is this:
{
"dogs": [{"name": "Bella"}, {"name": "Lucy"}],
"cats": [{"name": "Oscar"}, {"name": "Coco"}]
}
Then the problem with your code is merely this line:
let animals = try JSONDecoder().decode([Animal].self, from: response.data!)
You're claiming that the JSON represents an array of Animal. But it doesn't. It represents a dictionary with keys dogs
and cats
. So you just say so.
struct Animal: Codable {
let name: String
}
struct Animals: Codable {
let dogs: [Animal]
let cats: [Animal]
}
Now everything will just work:
let animals = try JSONDecoder().decode(Animals.self, from: response.data!)
推荐阅读
- apache - 如何将长网址重定向到短网址,但将长网址提供给客户端?
- reactjs - 无论我做什么,盖茨比都没有创建盖茨比页面
- django - forms.py 使用 ForeignKey 模型创建表单。商店应该只能将产品添加到自己的商店。(姜戈)
- python - 我如何知道 Databricks 文件系统 (DBFS) 文件存储格式?
- javascript - Chart JS 3.5.x 中的 beforeDraw
- asp.net-web-api - 尝试从 .net 框架 Web api 下载时 Excel 文件已损坏
- scala - 按键聚合数据集并列出其余值
- javascript - 如何在 React 中的按钮单击事件上发出 axios 获取请求?
- git - 将文件上传到 Elastic Beanstalk Quellbundle
- javascript - 在 react 项目中验证和验证 otp 后调用 props 函数