简体   繁体   中英

Parse JSON with Decodable return empty Model

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

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM