Decoding JSON array of different types in Swift

后端 未结 3 865
夕颜
夕颜 2020-12-18 12:36

I\'m trying to decode the following JSON Object

{
    \"result\":[
             {
             \"rank\":12,
             \"user\":{ 
                     \"n         


        
3条回答
  •  梦毁少年i
    2020-12-18 13:41

    Just for fun:

    First you need structs for the users and the representation of the first and second dictionary in the result array. The key "1" is mapped to one

    struct User : Decodable {
        let name : String
        let age : Int
    }
    
    struct FirstDictionary : Decodable {
        let rank : Int
        let user : User
    }
    
    struct SecondDictionary : Decodable {
        let one : [User]
    
        private enum CodingKeys: String, CodingKey { case one = "1" }
    }
    

    Now comes the tricky part:

    • First get the root container.
    • Get the container for result as nestedUnkeyedContainer because the object is an array.
    • Decode the first dictionary and copy the values.
    • Decode the second dictionary and copy the values.

      struct UserData: Decodable {
      
          let rank : Int
          let user : User
          let oneUsers : [User]
      
         private enum CodingKeys: String, CodingKey { case result }
      
          init(from decoder: Decoder) throws {
              let container = try decoder.container(keyedBy: CodingKeys.self)
              var arrayContainer = try container.nestedUnkeyedContainer(forKey: .result)
              let firstDictionary = try arrayContainer.decode(FirstDictionary.self)
              rank = firstDictionary.rank
              user = firstDictionary.user
              let secondDictionary = try arrayContainer.decode(SecondDictionary.self)
              oneUsers = secondDictionary.one
          }
      }
      

    If this code is preferable over traditional manual JSONSerialization is another question.

提交回复
热议问题