【发布时间】:2020-06-03 02:36:14
【问题描述】:
我的 User 结构是这样声明的。我们如何使用JSONdecoder 解码数组?
我收到 typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
This is my json data:
// http://localhost:1337/user/5eca2fa01583786f1c0ee1bc
[
{
"id": "5eca2fa01583786f1c0ee1bc",
"fullName": "Raj Shrestha",
"emailAddress": "raj@yahoo.com",
"following": [
],
"followers": [
{
"id": "5eca2f451583786f1c0ee1ba",
"fullName": "Udin Rajkarnikar",
"emailAddress": "udin@gmail.com"
}
],
"isFollowing": true
},
[
{
"createdAt": 1590581837003,
"updatedAt": 1590581837003,
"id": "5ece5a4d6e2e801e95365d50",
"text": "I love waterfalls",
"imageUrl": "https://nepgram-bucket.s3.amazonaws.com/a121f7-6854-4fe9-bc8e-defce029d",
"user": {
"id": "5eca2fa01583786f1c0ee1bc",
"fullName": "Raj Shrestha",
"emailAddress": "raj@yahoo.com"
}
},
{
"createdAt": 1590334928984,
"updatedAt": 1590334928984,
"id": "5eca95d08538288438c63779",
"text": "Creating post from iphone",
"imageUrl": "https://nepgram-bucket.s3.amazonaws.com/2badfb0e-de49-4b6c-ae1-0c6",
"user": {
"id": "5eca2fa01583786f1c0ee1bc",
"fullName": "Raj Shrestha",
"emailAddress": "raj@yahoo.com"
}
},
{
"createdAt": 1590308888243,
"updatedAt": 1590308888243,
"id": "5eca30181583786f1c0ee1bf",
"text": "asdasd",
"imageUrl": "https://nepgram-bucket.s3.ap-south-1.amazonaws.com/83b7e688b-4d37-a368-3b8b4526bd58.png",
"user": {
"id": "5eca2fa01583786f1c0ee1bc",
"fullName": "Raj Shrestha",
"emailAddress": "raj@yahoo.com"
}
}
]
]
struct User: Decodable {
let id : String
let fullName: String
let emailAddress: String
var isFollowing: Bool?
var followers, following: [User]?
var post: [Post]?
}
struct Post: Decodable {
let id: String
let createdAt: Int
let text: String
let user: User
let imageUrl: String
}
let user = try JSONDecoder().decode([User].self, from: data)
print(user)
【问题讨论】:
-
你能添加你试图解码的 JSON 对象吗?
-
我已经添加了 JSON 文件。
-
JSON 与模型不匹配。没有键
post并且将异构数组作为根对象无论如何都是一个坏主意。 -
我认为问题在于您的 JSON 无效,根是数组,模型与 JSON 不匹配。
-
我发现了问题。谢谢大家!