1

I'm trying to load local JSON file and parse using model which conforms to Decodable protocol.

JSON file:

[
{
    "body": {},
    "header": {
        "returnCode": "200",
        "returnMessage": "Successfully Received",
    }
}
]

Response Message model:

struct ResponseMessage: Decodable {

    struct header: Decodable {
        let returnCode: String
        let returnMessage: String
    }
}

Mock API implementation:

let url = Bundle.main.url(forResource: "MockJSONData", withExtension: "json")!
            do {
                let data = try Data(contentsOf: url)
                let teams = try JSONDecoder().decode(ResponseMessage.self, from: data)
                print(teams)
            } catch {
                print(error)
            }

But Response Message returns empty data for that.

Appreciate your help and suggestions!

Thanks

B K.
  • 534
  • 5
  • 18
Harshal Wani
  • 2,249
  • 2
  • 26
  • 41
  • 9
    Your JSON is an array, so it should be `decode([ResponseMessage].self`, and it's missing `struct ResponseMessage: Decodable { let header: header }`. And btw, write `struct Header: Decodable {` instead with an uppercase, and then `struct ResponseMessage: Decodable { let header: Header }` – Larme Aug 27 '19 at 05:45

1 Answers1

5

Update ResponseMessage and Header types as below,

struct ResponseMessage: Decodable {
    var header: Header
}


struct Header: Decodable {
    let returnCode: String
    let returnMessage: String
}

and decode like this,

do {
    let data = try Data(contentsOf: url)
    let teams = try JSONDecoder().decode([ResponseMessage].self, from: data)
    print(teams.first!.header.returnMessage)
} catch {
    print(error)
}
Kamran
  • 14,987
  • 4
  • 33
  • 51