空对象阻止 JSON 可解码在 swift 中工作
Null object is preventing JSON decodable from working in swift
有没有办法绕过空对象以确保可解码 JSON 正常工作?我附上了 JSON.
的图片
import UIKit
struct SearchResultData: Decodable {
let server_response_time: Int
let data: [SearchResultType]
let success: Bool
}
struct SearchResultType: Decodable {
let group: String
let data: [Movie]
}
struct Movie: Decodable {
let title: String
}
我在 运行 应用程序时收到此错误。
Failed to decode JSON: keyNotFound(CodingKeys(stringValue: "title", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 2", intValue: 2), CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))
这个
: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))
意味着 title
在某些部分是 nil
所以让它成为
let title: String?
您可能还需要
let data: [SearchResultType?]
因为 data
键也包含一些空值
只需将 structs
中可能包含 nils 的类型更改为可选类型
struct SearchResultData: Decodable {
let server_response_time: Int
let data: [SearchResultType]
let success: Bool
}
struct SearchResultType: Decodable {
let group: String
let data: [Movie]
}
struct Movie: Decodable {
let title: String? // this is nullable variable,
}
debugDescription: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))<-- as this line says
有没有办法绕过空对象以确保可解码 JSON 正常工作?我附上了 JSON.
的图片import UIKit
struct SearchResultData: Decodable {
let server_response_time: Int
let data: [SearchResultType]
let success: Bool
}
struct SearchResultType: Decodable {
let group: String
let data: [Movie]
}
struct Movie: Decodable {
let title: String
}
我在 运行 应用程序时收到此错误。
Failed to decode JSON: keyNotFound(CodingKeys(stringValue: "title", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 2", intValue: 2), CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))
这个
: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))
意味着 title
在某些部分是 nil
所以让它成为
let title: String?
您可能还需要
let data: [SearchResultType?]
因为 data
键也包含一些空值
只需将 structs
struct SearchResultData: Decodable {
let server_response_time: Int
let data: [SearchResultType]
let success: Bool
}
struct SearchResultType: Decodable {
let group: String
let data: [Movie]
}
struct Movie: Decodable {
let title: String? // this is nullable variable,
}
debugDescription: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))<-- as this line says