代码之家  ›  专栏  ›  技术社区  ›  Damian Dudycz

使用decodable进行自定义json解码

  •  2
  • Damian Dudycz  · 技术社区  · 7 年前

    json

    {  
       "route":{  
          "1":"Atrakcyjno\u015b\u0107 przyrodnicza",
          "2":"Atrakcyjno\u015b\u0107 kulturowa",
          "3":"Dla rodzin z dzie\u0107mi",
          "5":"Dla senior\u00f3w",
          "6":"Dla or\u0142\u00f3w",
          "8":"Niepe\u0142nosprawni"
       },
       "apartments":{  
          "1":"WifI",
          "4":"Gastronomia",
          "5":"Parking",
          "6":"Dla niepe\u0142nosprawnych",
          "7":"Dla rodzin z dzie\u0107mi",
          "8":"Dla senior\u00f3w"
       },
       "levels":{  
          "1":"\u0141atwy",
          "2":"\u015aredni",
          "3":"Trudny",
          "4":"Bardzo trudny"
       }
    }
    

    我想把它解码得尽可能简单,但我不知道如何解码这些子字典。这些是 dicts ,但它应该是 array

    struct PreferencesList: Decodable {
    
        private enum CodingKeys: String, CodingKey {
            case routes     = "route"
            case apartments
            case levels
        }
    
        let routes:     [Preference]
        let apartments: [Preference]
        let levels:     [Preference]
    }
    
    struct Preference: Decodable {
        let id:   Int
        let name: String
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Jack    7 年前

    我想你需要一步一步地做。

    保持结构不变。 Preference 不需要这样 Decodable . 然后,覆盖 init(from decoder: Decoder) throws 功能如下。

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let routes = try container.decode([String: String].self, forKey: .routes)
        self.routes = []
        for (key, value) in routes {
            self.routes.append(Preference(id: key, name: value))
        }
        // Do the same for other var...
    }
    

    我希望这有帮助。