0

I have a json array that contains different type of object. I don't have any chance to change the end point. I am using the AFNetworking. I want to display product detail according to the Product.type field. But I can't parse the json. AFNetworking throws an error: 417 - Expectation Failed

Is it possible to parse it?

Here is the generic AF request method:

@discardableResult
private static func performRequest<T:Decodable>(route:APIRouter, decoder: JSONDecoder = JSONDecoder(), completion:@escaping (Result<T, AFError>)->Void) -> DataRequest {
    return AF.request(route)
        .responseDecodable (decoder: decoder){ (response: DataResponse<T, AFError>) in completion(response.result)
    }
}

static func getProduct(id:Int, completion:@escaping (Result<Product, AFError>)->Void){
    performRequest(route: APIRouter.getProduct(id: id), completion: completion)
}

My struct is:

struct Product: Codable {
    let id: Int
    let type: Int 
    let details: [Detail1] // this array can contain Detail1, Detail2, Detail3 in any order
}

struct Detail1: Codable {
        let id: Int
        let name: String
        let surname: String
}

struct Detail2: Codable {
        let id: Int
        let title: String
        let subtitle: String
}

struct Detail3: Codable {
        let id: Int
        let thickness: Int
        let length: Int
}

I know my struct doesn't reflect the json string. Here is the full JSON String:

{"id": "ST_34", "users" : [{"name" : "Foo", "surname" : "Bar"}],
 "products" :[
              {"id": 268, "type" : "XDFT", 
                        "details" : [{"id": 1, "name" : "xray", "surname" : "TRvb"}]
              },
{"id": 764, "type" : "ZRFT", 
                        "details" : [{"id": 27, "thickness" : 2, "length" : 12}]
              }
             ]
}
uzman
  • 51
  • 1
  • 4
  • Show the JSON data the API is trying to get. – George Aug 22 '21 at 19:20
  • 3
    So many backends send so many inconsistent data. I recommend an enum with associated values. – vadian Aug 22 '21 at 19:24
  • I added the full json string. – uzman Aug 22 '21 at 19:54
  • 2
    did you check out that? https://stackoverflow.com/questions/52681385/swift-codable-multiple-types/52681527 – Adem Özsayın Aug 22 '21 at 21:26
  • Lets face it: your `decode` is going to be a mess. To make it somewhat bearable youl should make your `Detailx` structs derive from a common base struct (e.g. `Detail`) or at the very least conform to the same protocol. You will then need a custom `init(...)` method with a lot of `try?`s or some custom `switch` to have this decode in any useful manner. However in order for anyone to help you should provide some JSON that covera all cases (and provides heterogeneous arrays if they are to be allowed). – Patru Aug 25 '21 at 02:05

0 Answers0