Decodable for JSON with two structs under the same tag

前端 未结 3 1461
灰色年华
灰色年华 2021-01-27 08:44

I have this json:

{ \"stuff\": [
 {
 \"type\":\"car\",
 \"object\":{
  \"a\":66,
  \"b\":66,
  \"c\":66 }},
 {
 \"type\":\"house\",
 \"object\":{
  \"d\":66,
  \         


        
3条回答
  •  生来不讨喜
    2021-01-27 09:06

    You can handle multiple cases by using the enum just define your type, Giving code will help you to parse the JSON by using Struct modal with enum.

    // MARK: - Welcome
    struct Welcome: Codable {
        let stuff: [Stuff]
    }
    
    // MARK: - Stuff
    struct Stuff: Codable {
        let type: String
        let object: Object
    }
    
    // MARK: - Object
    struct Object: Codable {
        let a, b, c, d: Int?
        let e, f: Int?
    }
    
    enum Type: String {
        case car
        case house
    }
    
    func fetchResponse() {
        do {
            let jsonString = "your json string"
            let data = Data(jsonString.utf8)
            let result = try JSONDecoder().decode(Welcome.self, from: data)
            let objects = result.stuff
            let carObjects = objects.filter{$0.type == Type.car.rawValue}
            print("Its car array: \(carObjects)")// if you need filters car object then use this
            let houseObjects = objects.filter{$0.type == Type.house.rawValue}// if you need filters house object then use this
            print("Its house array: \(houseObjects)")
            // or you check in loop also
            objects.forEach { (stuff) in
                switch stuff.type {
                case Type.car.rawValue:
                    print("Its car object")
                case Type.house.rawValue:
                    print("Its house object")
                default:
                    print("Also you can set your one case in `default`")
                    break
                }
            }
        } catch {
            print(error.localizedDescription)
        }
    }
    

提交回复
热议问题