Response Serialization error, how to fix it?

1.9k views Asked by At

I am trying to decode a json data, but it throws an error:

[] nw_protocol_get_quic_image_block_invoke dlopen libquic failed responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))))

I think, I did it in a correct way, I checked for the type mismatch also, looks correct, but could not comprehend why am i still getting the error. .

here is how my json data response looks like:

[
{
    "id": 1,
    "name": "BlackJet",
    "type": "Silk",
    "quantity": "100"
},
 [
{
    "id": 2,
    "name": "Toto",
    "type": "Leather",
    "quantity": "10"
}, 

 ...,
 ]

here is my struct data:

 import Foundation

 struct Response<T: Codable>: Codable {
     var data: [T]?
  }

 struct MyData: Codable {
     var id: Int
     var name: String
     var type: String
     var quantity: Int
  }

and my serverCommunicator func:

static func getData() -> Promise<Response<MyData>> {
    let decoder = JSONDecoder()
    return Promise { seal in
        AF.request(API.getData, method: .get, parameters: .none).responseDecodable(of: Response<MyData>.self, decoder: decoder) { response in
            switch response.result {
                case .success(let val):
                    return seal.fulfill(val)
                case .failure(let err):
                    return seal.reject(err)
            }
        }
    }
}

and my apiCall func inside VC didload:

func getData() {
    ServerCommunicator.getData().done  { response -> Void in
        guard response.data != nil, let data = response.data else {
            print("Data could not be obtained.. .")
            return
        }
        self.data = data
    }.catch { (err) in
        print(err)
    }
}
   

NOTE: No api headers or parametrs exist in my api//

1

There are 1 answers

0
Kamran On

First you need to change the type of quantity from Int to String as per the response,

 struct MyData: Codable {
     var id: Int
     var name: String
     var type: String
     var quantity: String
  }

Then you will need to change the signature of getData method as below,

static func getData() -> Promise<[MyData]> {
    let decoder = JSONDecoder()
    return Promise { seal in
        AF.request(API.getData, method: .get, parameters: .none).responseDecodable(of: [MyData].self, decoder: decoder) { response in
            switch response.result {
                case .success(let val):
                    return seal.fulfill(val)
                case .failure(let err):
                    return seal.reject(err)
            }
        }
    }
}