我收到一个Swift解码错误:解析JSON,发现一个需要字典的数组? [英] I get an Swift Decoding error: parsing JSON, found an Array expected a Dictionary?
问题描述
我收到此错误:
" typeMismatch(Swift.Dictionary< Swift.String,Any>,Swift.DecodingError.Context(codingPath:[],debugDescription:希望对Dictionary< String,Any>进行解码,但是找到了一个数组.",底层错误:nil))"
"typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))"
在解码JSON时迅速(来自django rest框架).
In swift while decoding JSON (from django rest framework).
这是json:
[
{
"id": 1,
"title": "1e todo",
"description": "1e todo test"
},
{
"id": 2,
"title": "2e todo",
"description": "2e todo test"
}
]
这是Swift中的解析函数:
This is the parse function in Swift:
func parseJSON(todoData:Data){
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(ToDoData.self, from: todoData)
fetchedTitle = decodedData.todoitems[1].title
print(fetchedTitle)
Swift中的结构:
And the Structs in Swift:
import Foundation
struct ToDoData: Decodable {
//return een list met ToDoData
let todoitems: [Items]
}
struct Items: Decodable {
//return een list met ToDoData
let id: String
let title: String
let description: String
}
因此,俗话说找到了一个数组,但是我怎样才能找到标题"?在JSON文件中.
So its saying found an Array, but how can i get to the "Title" in the JSON file.
推荐答案
您的json似乎是 Items
的数组,而不是具有名为 todoitems
的属性的对象,请改为这样做:
Your json seems to be an array of Items
, and not an object with a property named todoitems
, so do this instead:
let decodedData = try decoder.decode([Items].self, from: todoData)
fetchedTitle = decodedData[1].title
您的 ToDoData
结构不能在这种情况下使用,因为您的json不包含名为 todoitems
的属性.
Your ToDoData
struct can't be used in this scenario, since your json doesn't contain a property named todoitems
.
这篇关于我收到一个Swift解码错误:解析JSON,发现一个需要字典的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!