解析复杂的json代码 [英] Parse complex json code

查看:49
本文介绍了解析复杂的json代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 JSON 代码并想在 Swift 中解析它.我使用 Alamofire 来获取 JSON 并为解析创建了一个结构:

I have the following JSON code and want to parse it in Swift. I use Alamofire to get the JSON and have created a struct for the parsing:

    {  
   "-8802586561990153106-1804221538-5":{  
      "zug":{  
         "klasse":"RB",
         "nummer":"28721"
      },
      "ankunft":{  
         "zeitGeplant":"1804221603",
         "zeitAktuell":"1804221603",
         "routeGeplant":[  
            "Wiesbaden Hbf",
            "Mainz Hbf"
         ]
      },
      "abfahrt":{  
         "zeitGeplant":"1804221604",
         "zeitAktuell":"1804221604",
         "routeGeplant":[  
            "Gro\u00df Gerau",
            "Klein Gerau",
            "Weiterstadt"
         ]
      }
   },
   "8464567322535526441-1804221546-15":{  
      "zug":{  
         "klasse":"RB",
         "nummer":"28724"
      },
      "ankunft":{  
         "zeitGeplant":"1804221657",
         "zeitAktuell":"1804221708",
         "routeGeplant":[  
            "Aschaffenburg Hbf",
            "Mainaschaff"
         ]
      },
      "abfahrt":{  
         "zeitGeplant":"1804221658",
         "zeitAktuell":"1804221709",
         "routeGeplant":[  
            "Mainz-Bischofsheim"
         ]
      }
   }
}

我为此创建了一个结构,如下所示:

I have created a struct for this that looks like this:

struct CallResponse: Codable {
    struct DirectionTrain: Codable {
        struct Train: Codable {
            let trainClass: String
            let trainNumber: String
        }
        struct Arrival: Codable {
            let line: String
            let eta: Date
            let ata: Date
            let platform: String
            let route: [String]
        }
        struct Departure: Codable {
            let line: String
            let etd: Date
            let atd: Date
            let platform: String
            let route: [String]
        }
    }
 }

我的其余代码是:

 Alamofire.request(url!).responseJSON { response in
            switch response.result {
            case .success:
                let decoder = JSONDecoder()
                let parsedResult = try! decoder.decode(CallResponse.self, from: response.data!)
            case .failure(let error):
                print(error)
            }
        }

当我运行此代码时,错误消息是:

When I run this code the error message is:

Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "train", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"train\", intValue: nil) (\"train\").", underlyingError: nil))

谁能帮我找到我的问题?感谢您的回答!

Can anyone help me find my problem? Thank you for your answers!

推荐答案

问题仅仅是你的结构看起来一点也不像你的 JSON!

The problem is merely that your structs look nothing at all like your JSON!

您的 JSON 是一个字典,其键的名称类似于 "-8802586561990153106-1804221538-5""8464567322535526441-1804221546-15".但我没有看到您声明任何处理这些键的结构.

Your JSON is a dictionary whose keys have names like "-8802586561990153106-1804221538-5" and "8464567322535526441-1804221546-15". But I don't see you declaring any struct that deals with those keys.

然后每个结果都是一个字典,其中包含诸如 "zug""ankunft""abfahrt" 之类的键.但我也没有看到您声明任何处理这些键的结构.

Then each of those turns out to be a dictionary with keys like "zug", "ankunft", and "abfahrt". But I don't see you declaring any struct that deals with those keys either.

然后"zug"有键"klasse""nummer";你也没有.

And then the "zug" has keys "klasse" and "nummer"; you don't have those either.

等等.

要么你的结构必须看起来和你的 JSON 完全一样,要么你必须定义 CodingKeys 并且可能还实现 init(from:) 来处理你的结构和你的 JSON 之间的任何差异.我怀疑键 "-8802586561990153106-1804221538-5""8464567322535526441-1804221546-15" 可能是不可预测的,所以你会编写 init(from:) 来处理它们.

Either your structs must look exactly like your JSON, or else you must define CodingKeys and possibly also implement init(from:) to deal with any differences between your structs and your JSON. I suspect that the keys "-8802586561990153106-1804221538-5" and "8464567322535526441-1804221546-15" are unpredictable, so you will probably have to write init(from:) in order to deal with them.

例如,我能够像这样解码你的 JSON(我真的不推荐使用 try!,但我们解码没有错误,这只是一个测试):

For example, I was able to decode your JSON like this (I do not really recommend using try!, but we decoded without error and it's just a test):

    struct Entry : Codable {
        let zug : Zug
        let ankunft : AnkunftAbfahrt
        let abfahrt : AnkunftAbfahrt
    }
    struct Zug : Codable {
        let klasse : String
        let nummer : String
    }
    struct AnkunftAbfahrt : Codable {
        let zeitGeplant : String
        let zeitAktuell : String
        let routeGeplant : [String]
    }
    struct Top : Decodable {
        var entries = [String:Entry]()
        init(from decoder: Decoder) throws {
            struct CK : CodingKey {
                var stringValue: String
                init?(stringValue: String) {
                    self.stringValue = stringValue
                }
                var intValue: Int?
                init?(intValue: Int) {
                    return nil
                }
            }
            let con = try! decoder.container(keyedBy: CK.self)
            for key in con.allKeys {
                self.entries[key.stringValue] = 
                    try! con.decode(Entry.self, forKey: key)
            }
        }
    }
    // d is a Data containing your JSON
    let result = try! JSONDecoder().decode(Top.self, from: d)

这篇关于解析复杂的json代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆