Correctly Parsing JSON in Swift 3

前端 未结 9 962
甜味超标
甜味超标 2020-11-21 07:00

I\'m trying to fetch a JSON response and store the results in a variable. I\'ve had versions of this code work in previous releases of Swift, until the GM version of Xcode 8

9条回答
  •  情话喂你
    2020-11-21 07:54

    {
        "User":[
          {
            "FirstUser":{
            "name":"John"
            },
           "Information":"XY",
            "SecondUser":{
            "name":"Tom"
          }
         }
       ]
    }
    

    If I create model using previous json Using this link [blog]: http://www.jsoncafe.com to generate Codable structure or Any Format

    Model

    import Foundation
    struct RootClass : Codable {
        let user : [Users]?
        enum CodingKeys: String, CodingKey {
            case user = "User"
        }
    
        init(from decoder: Decoder) throws {
            let values = try? decoder.container(keyedBy: CodingKeys.self)
            user = try? values?.decodeIfPresent([Users].self, forKey: .user)
        }
    }
    
    struct Users : Codable {
        let firstUser : FirstUser?
        let information : String?
        let secondUser : SecondUser?
        enum CodingKeys: String, CodingKey {
            case firstUser = "FirstUser"
            case information = "Information"
            case secondUser = "SecondUser"
        }
        init(from decoder: Decoder) throws {
            let values = try? decoder.container(keyedBy: CodingKeys.self)
            firstUser = try? FirstUser(from: decoder)
            information = try? values?.decodeIfPresent(String.self, forKey: .information)
            secondUser = try? SecondUser(from: decoder)
        }
    }
    struct SecondUser : Codable {
        let name : String?
        enum CodingKeys: String, CodingKey {
            case name = "name"
        }
        init(from decoder: Decoder) throws {
            let values = try? decoder.container(keyedBy: CodingKeys.self)
            name = try? values?.decodeIfPresent(String.self, forKey: .name)
        }
    }
    struct FirstUser : Codable {
        let name : String?
        enum CodingKeys: String, CodingKey {
            case name = "name"
        }
        init(from decoder: Decoder) throws {
            let values = try? decoder.container(keyedBy: CodingKeys.self)
            name = try? values?.decodeIfPresent(String.self, forKey: .name)
        }
    }
    

    Parse

        do {
            let res = try JSONDecoder().decode(RootClass.self, from: data)
            print(res?.user?.first?.firstUser?.name ?? "Yours optional value")
        } catch {
            print(error)
        }
    

提交回复
热议问题