通过可编码协议解析JSON

时间:2019-02-22 09:26:27

标签: ios json swift codable

我对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;
}
)
]

如何通过可编码协议解析它?

下面是我的代码:

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
}

这就是我解析数据的方式

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)

但是所有相同的allNews都为零,尽管新闻数据以上面附带的json的形式传给我

2 个答案:

答案 0 :(得分:0)

您将收到以下格式的回复:

[ "allNews": (
    {
        key : value
    },
    {
        key : value
    }
)]

由于您的新闻数组位于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)

答案 1 :(得分:-1)

这应该有助于您解析数据

let value = response.data

do {
    let allValues = try JSONDecoder().decode([DetailNews].self, from: value)
} catch let error {
     print(error)
}

确保值的类型为数据