-2

I am using the following code to decode the data from server to json. But when it is parsing into json. It throws following error

The data couldn’t be read because it isn’t in the correct format.

struct ExpoDecode: Codable {

var success: Bool?
var count: Int?
var type: String?
var results: [Expo]?

enum CodingKeys: String, CodingKey {

    case success = "Success"
    case count = "Count"
    case type = "Type"
    case results = "Results"
}
}

struct ExpoAsset: Codable {

var assetId: String?
var asseturl: String?

enum CodingKeys: String, CodingKey {

    case assetId = "ExpoAssetId"
    case asseturl = "AsstetUrl"
}
}

struct Expo: Codable {

var id: String?
var name: String?
var location: String?
var timing: String?

var expoAssets: [ExpoAsset]?

enum CodingKeys: String, CodingKey {

    case id = "Expoid"
    case name = "Expotitle"
    case location = "Location"
    case ticketCost = "Ticketcost"
    case expoAssets = "ExpoAssets"
}

init(from decoder: Decoder) throws {

    let values = try decoder.container(keyedBy: CodingKeys.self)

    id = try values.decode(String.self, forKey: .id)
    name = try values.decode(String.self, forKey: .name)
    location = try values.decode(String.self, forKey: .location)
    ticketCost = try values.decode(String.self, forKey: .ticketCost)
    discount = try values.decode(String.self, forKey: .discount)
    startTime = try values.decode(String.self, forKey: .startTime)
    endTime = try values.decode(String.self, forKey: .endTime)

    expoAssets = try values.decode([ExpoAsset].self, forKey: .expoAssets)

}
}

And Decoding part is

let expoResult = try decoder.decode(ExpoDecode.self, from: data!)

Please help to identify the issue

Balaji Kondalrayal
  • 1,743
  • 3
  • 19
  • 38

1 Answers1

2

Use try/catch handler to handle the error thrown by decoding and log it to console. You can see where exactly the issue is in your decoding process, if error is due to decoding json.

do {
  let expoResult = try decoder.decode(ExpoDecode.self, from: data!)
} catch {
  print("Error occurred: \(error)") // notice this line which will help you hunt for error
}
Sandeep
  • 20,908
  • 7
  • 66
  • 106
  • Ok, so did you try to log the error from decoder like I have shown above. – Sandeep Mar 06 '18 at 11:39
  • Yes. The error is dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}))) – Balaji Kondalrayal Mar 06 '18 at 11:42