解码器未在关键路径解码 json
Decoder not decoding json at keypath
我正在尝试解码一些 JSON,但它没有解析它。我认为它可能与不正确的 KeyPath 或对象本身有关。但是我想不通。
这是我要解码的 JSON(我想要文档路径中的数组):
{
"status": 200,
"data": {
"docs": [
{
"_id": "60418a6ce349d03b9ae0669e",
"title": "Note title",
"date": "2015-03-25T00:00:00.000Z",
"body": "this is the body of my note.....",
"userEmail": "myemail@gmail.com"
}
],
"total": 1,
"limit": 20,
"page": 1,
"pages": 1
},
"message": "Notes succesfully Recieved"
}
这是我的解码函数:
extension JSONDecoder {
func decode<T: Decodable>(_ type: T.Type, from data: Data, keyPath: String) throws -> T {
let toplevel = try JSONSerialization.jsonObject(with: data)
if let nestedJson = (toplevel as AnyObject).value(forKeyPath: keyPath) {
let nestedJsonData = try JSONSerialization.data(withJSONObject: nestedJson)
return try decode(type, from: nestedJsonData)
} else {
throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Nested json not found for key path \"\(keyPath)\""))
}
}
}
我这样称呼它:
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let notes = try decoder.decode([Note].self, from: data, keyPath: "data.docs")
最后,这是我的笔记结构:
struct Note: Codable {
var title: String?
let date: Date?
var body: String?
let userEmail: String?
}
问题是我试图将日期解码为 Date 对象而不是 JSON.
中显示的字符串
谢谢@vadian!
我正在尝试解码一些 JSON,但它没有解析它。我认为它可能与不正确的 KeyPath 或对象本身有关。但是我想不通。
这是我要解码的 JSON(我想要文档路径中的数组):
{
"status": 200,
"data": {
"docs": [
{
"_id": "60418a6ce349d03b9ae0669e",
"title": "Note title",
"date": "2015-03-25T00:00:00.000Z",
"body": "this is the body of my note.....",
"userEmail": "myemail@gmail.com"
}
],
"total": 1,
"limit": 20,
"page": 1,
"pages": 1
},
"message": "Notes succesfully Recieved"
}
这是我的解码函数:
extension JSONDecoder {
func decode<T: Decodable>(_ type: T.Type, from data: Data, keyPath: String) throws -> T {
let toplevel = try JSONSerialization.jsonObject(with: data)
if let nestedJson = (toplevel as AnyObject).value(forKeyPath: keyPath) {
let nestedJsonData = try JSONSerialization.data(withJSONObject: nestedJson)
return try decode(type, from: nestedJsonData)
} else {
throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Nested json not found for key path \"\(keyPath)\""))
}
}
}
我这样称呼它:
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let notes = try decoder.decode([Note].self, from: data, keyPath: "data.docs")
最后,这是我的笔记结构:
struct Note: Codable {
var title: String?
let date: Date?
var body: String?
let userEmail: String?
}
问题是我试图将日期解码为 Date 对象而不是 JSON.
中显示的字符串谢谢@vadian!