首页 > 解决方案 > Swift Json KeyNotFound

问题描述

请帮助完成这项工作我一直在尝试找出 JSON 和 Swift 一个星期,并且今天到目前为止面对这个问题 5 个小时。

收到错误

解码 JSON 时出错 keyNotFound(CodingKeys(stringValue: "MP", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "MP", intValue: nil) (“MP”)。”,基础错误:无))

年为零

代码

struct UserDay: Codable {
    let MP: UserMP
    let WP: UserWP
}

struct UserMP: Codable {
    let M: [UserM]
    let S: [UserS]
}

struct UserM : Codable {
    let title: String
    let description: String
    let time: String
}

struct UserS : Codable {
    let title: String
    let description: String
    let time: String
}

struct UserWP: Codable {
    let WP: [WPData]
}

struct WPData: Codable {
    let title: String
    let values: [Int]
}
class LogDataHandler {
    public func grabJSONInfo(){
        guard let jsonURL = Bundle(for: type(of: self)).path(forResource: "newLogData", ofType: "json") else { return }
        
        guard let jsonString = try? String(contentsOf: URL(fileURLWithPath: jsonURL), encoding: String.Encoding.utf8) else { return }

//        print(jsonString)
        // Print Info for TESTING
        var year: UserDay?
        
        do {
            year = try JSONDecoder().decode(UserDay.self, from: Data(jsonString.utf8))
        } catch {
            print("ERROR WHEN DECODING JSON \(error)")
        }
        
        guard let results = year else {
            print("YEAR IS NIL")
            return
        }
        
        print(results)   
    }
}

JSON

{
    "01/01/2020": {
   
        "MP" : {
            "M" : [
                {"title" : "m1", "description" : "1", "time" : "12:30pm"},
                {"title" : "m2", "description" : "2", "time" : "1:30pm"},
                {"title" : "m3", "description" : "3", "time" : "2:30pm"}
            ],
            "S" : [
                {"title" : "s1", "description" : "1", "time" : "1pm"}
            ]
        },
        "WP" : [
            { "title" : "abc", "values" :  [12, 10, 6]},
            { "title" : "def", "values" :  [8]}
        ]
    },
    "01/29/2020": {
        
        "MP" : {
            "M" : [{"title" : "m1", "description" : "1", "time" : "12:30pm"}],
            "S" : [{"title" : "s1", "description" : "1", "time" : "12:30pm"}]
        },
        "WP" :[{ "title" : "def", "values" :  [8]}]
    }
    
}

标签: jsonswiftstructenumskey

解决方案


首先,let WP: UserWP用数组替换:

struct UserDay: Codable {
    let MP: UserMP
    let WP: [WPData]
}

然后解码[String:UserDay]而不是UserDay

try JSONDecoder().decode([String:UserDay].self, from: Data(jsonString.utf8))

请注意,这将返回一个带有键值对的字典"01/01/2020": UserDay object

这意味着您不能将字典分配给[String: UserDay]变量UserDay。相反,您可以通过某个日期的键(例如“01/01/2020”)访问字典,然后将其分配给您的UserDay变量:

let result = try JSONDecoder().decode([String:UserDay].self, from: Data(jsonString.utf8))
let someYear = result["01/01/2020"]

请注意, someYear 将是可选的,因此您可能需要提供默认值或强制解包它。


推荐阅读