【问题标题】:Decoder not decoding json at keypath解码器未在 keypath 处解码 json
【发布时间】:2021-03-05 17:22:41
【问题描述】:

我正在尝试解码一些 JSON,但它没有解析它。我认为它可能与不正确的 KeyPath 或对象本身有关。但我想不通。

这是我要解码的 JSON(我想要 docs 路径中的数组):

{
    "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")

最后,这是我的 Note Struct:

struct Note: Codable {
    var title: String?
    let date: Date?
    var body: String?
    let userEmail: String?
}

【问题讨论】:

  • ...给我一个错误。什么错误?并且转换 JSON 三次(2x JSONSerialization,1x JSONDecoder)比解码 JSON 一次并从嵌套结构中获取数组效率低得多。
  • 抱歉,无法解析。这就是我的意思。
  • @vadian 我知道它效率低下,但我发现这是一个有助于解析 json 深处的对象的函数。如果你有更好的,请告诉我。
  • 至少抓住DecodingError 并打印出来。您不能将包含小数秒的 IS08601 字符串中的 date 解码为 Date。解码String 或添加日期格式化程序和适当的日期解码策略。
  • @vadian 这就是问题所在!谢谢!

标签: json swift jsondecoder


【解决方案1】:

问题是我试图将日期解码为 Date 对象,而不是 JSON 上显示的字符串。

谢谢@vadian!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多