[英]Parse JSON via Codable protocol
I have an answer with Firebase in this form: 我有以下形式的Firebase答案:
["allNews": <__NSArrayM 0x6000015f06c0>(
{
createDate = "21.02.19";
creator = "lol@gmail.com";
creatorImageURL = "<null>";
creatorUID = kzorlyIOI3RgEjCV1XDLQUhu5CS2;
newsImageURL = "";
text = "Daft g s dfg ";
title = "Test ";
},
{
createDate = "21.02.19";
creator = "plol2@gmail.com";
creatorImageURL = "<null>";
creatorUID = Tw1JzFzcVbelRUA7GoFZ9CIWIwr1;
newsImageURL = "";
text = Vcbccvbvb;
title = hdbdvbccfb;
}
)
]
How can I parse it via the Codable protocol? 如何通过可编码协议解析它?
Below is my code: 下面是我的代码:
struct AllNews: Codable {
var allNews: [DetailNews]
}
struct DetailNews: Codable {
var creator: String
var creatorUID: String
var title: String
var text: String
var createDate: String
var creatorImageURL: String
var newsImageURL: String
}
that's how I parse the data 这就是我解析数据的方式
guard let newsData = try? JSONSerialization.data(withJSONObject: document.data(), options: []) else { return }
let decodeJSON = JSONDecoder()
let allNews = try? decodeJSON.decode([DetailNews].self, from: newsData)
print(allNews)
but all the same allNews comes nil although the news data comes to me in the form of json which is attached above 但是所有相同的allNews都为零,尽管新闻数据以上面附加的json的形式传给我
You are receiving response in format: 您收到以下格式的回复:
[ "allNews": (
{
key : value
},
{
key : value
}
)]
As your news array lies in allNews key so you should pass AllNews
struct to decode your response as: 由于您的新闻数组位于allNews键中,因此您应传递
AllNews
结构以将响应解码为:
guard let newsData = try? JSONSerialization.data(withJSONObject: document.data(), options: []) else { return }
let allNews = try? JSONDecoder().decode(AllNews.self, from: newsData)
print(allNews)
This should help you parse your data 这应该可以帮助您解析数据
let value = response.data
do {
let allValues = try JSONDecoder().decode([DetailNews].self, from: value)
} catch let error {
print(error)
}
Make sure value is of type Data 确保值是数据类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.