简体   繁体   English

Swift Json KeyNotFound

[英]Swift Json KeyNotFound

Please help make this work I've been trying to figure out JSON and Swift for a week and facing this problem for 5 hours so far today.请帮助完成这项工作我一直试图找出 JSON 和 Swift 一个星期,并且今天迄今为止面临这个问题 5 个小时。

Error Received收到错误

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

YEAR IS NIL一年为零

Code代码

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 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]}]
    }
    
}

First, replace let WP: UserWP with an array:首先,将let WP: UserWP替换为数组:

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

Then decode [String:UserDay] instead of UserDay :然后解码[String:UserDay]而不是UserDay

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

Note that this will return a dict with key-value pairs "01/01/2020" : UserDay object .请注意,这将返回一个带有键值对"01/01/2020"的字典: UserDay object

This means you can't assign a dictionary [String: UserDay] to a UserDay variable.这意味着您不能将字典[String: UserDay]分配给UserDay变量。 Instead you can access the dict by a key which is some date (eg. "01/01/2020") and then assign it to your UserDay variable:相反,您可以通过某个日期的键(例如“01/01/2020”)访问字典,然后将其分配给您的UserDay变量:

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

Note that someYear will be optional so you may want to provide a default value or force-unwrap it.请注意, someYear 将是可选的,因此您可能需要提供默认值或强制解包它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM