我正在尝试加载本地JSON
文件并使用符合Decodable
协议的模型进行解析。
JSON文件:
[ { "body": {}, "header": { "returnCode": "200", "returnMessage": "Successfully Received", } } ]
响应消息模型:
struct ResponseMessage: Decodable { struct header: Decodable { let returnCode: String let returnMessage: String } }
模拟API的实现:
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) }
但是响应消息为此返回空数据。
感谢您的帮助和建议!
谢谢
更新ResponseMessage
和Header
类型如下,
struct ResponseMessage: Decodable { var header: Header } struct Header: Decodable { let returnCode: String let returnMessage: String }
而decode
像这样的,
do { let data = try Data(contentsOf: url) let teams = try JSONDecoder().decode([ResponseMessage].self, from: data) print(teams.first!.header.returnMessage) } catch { print(error) }