How to Read value from response model of Codable

Viewed 64

print(name) gives me

Optional(TestProject.NameUnion.nameElementArray([TestProject.NameElement(firstKey: Optional(["DSR"]))])) 

How I can get firstKey value = DSR or name = Deepak Singh Rawat

Please help to parse name or name-> First key value from it

I am using codable class to decode json response from server

My Code to read and display response

        do{
            if let path = Bundle.main.path(forResource: "jsonfilename", ofType: "json"){
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
                let  abModel = try JSONDecoder().decode(NameModel.self, from: data)
                
                let  abModel = response
            let name = abModel?.first?.name
            print(name)


            }
        }catch{
            
            print("fail")
        }

My Json value

[ {
    "name": [{
        "First": [
            "DSR"
        ]
    }]
},{
        "name": "Deepak Singh Rawat"
    }
 ]

My Model for it

import Foundation // MARK: - NameModelElement struct NameModelElement: Codable { var name: NameUnion? }

// NameUnion.swift


enum NameUnion: Codable {
    case nameElementArray([NameElement])
    case string(String)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let x = try? container.decode([NameElement].self) {
            self = .nameElementArray(x)
            return
        }
        if let x = try? container.decode(String.self) {
            self = .string(x)
            return
        }
        throw DecodingError.typeMismatch(NameUnion.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for NameUnion"))
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .nameElementArray(let x):
            try container.encode(x)
        case .string(let x):
            try container.encode(x)
        }
    }
}


struct NameElement: Codable {
    var firstKey: [String]?

    enum CodingKeys: String, CodingKey {
        case firstKey = "First"
    }
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        firstKey = try values.decodeIfPresent([String].self, forKey: .firstKey)

    }
    
}



typealias NameModel = [NameModelElement]
0 Answers
Related