php - 固定 : JSON cannot decode array from php

标签 php ios json swift

JSON 解码器显示空列表,但所有内容均已正确编码。我从服务器获取了一个 json 数组,但在 Xcode 控制台中它仍然显示一个空数组。

News(news: [])

当来自服务器的当前响应是一个有效的 json 数组时:

{"news":[{"info_id":"unique id","title":"some title","description":"some description","date":"2019-07-10","time":"10:23:00"}]}

我解析 json 的结构是:

struct News: Codable {

let news = [Info]()

struct Info: Codable {

    let infoId: String
    let title: String
    let description: String
    let date: String
    let time: String

    private enum CodingKeys: String, CodingKey {
        case infoId = "info_id"
    }

}

我尝试使用该代码解码该帖子数组:

let decoder = JSONDecoder()
                let news: News = try decoder.decode(News.self, from: data)
                print("\(news)")

解决方案:let news = [Info]() 更改为 var news = [Info]()

最佳答案

试试这个。

    struct BaseNews: Codable {
    let news: [News]
}

// MARK: - News
struct News: Codable {
    let infoID, title, newsDescription, date: String
    let time: String

    enum CodingKeys: String, CodingKey {
        case infoID = "info_id"
        case title
        case newsDescription = "description"
        case date, time
    }
}


let decoder = JSONDecoder()
let news: News = try decoder.decode(BaseNews.self, from: data)

更新:根据您的评论

I cannot cast news to News when decoding because it might be more objects in the array

Codables 协议(protocol)需要对其主体内的属性进行显式声明,因为您无法解码比方说使用相同 key 或缺少 key 的多个类型,因此要么实现完整的 JSON decoding keys,或者浏览你的 json array 切片或者做任何你需要的事情来获得需要的数据的输出来解码。

现在通常当同一个数组中有多个对象类型时,应该有某种方法来判断哪个是什么,或者至少在对象之间有一个公共(public)键和一个可为空的值,而不会丢失任何键。

还有一种高级解码实践,例如从其解码器中覆盖一致性方的初始化器并手动创建容器并解码每个 key ,这将允许我们以我们喜欢的方式操作数据类型、 key 路径。

Side Note: it's considered bad practice for the web api to return an array that contains multiple objects types

关于php - 固定 : JSON cannot decode array from php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617048/

相关文章:

ios - 为什么我不能将 secureTextEntry 与 UTF-8 键盘一起使用?

python - 在 Python 中,如何通过删除括号和大括号来打印 Json

javascript - JQuery解析json多个对象

php - 在数据库中不存在行时在 PHP OOP 中插入查询

PHP:Unicode 强调字符和变音符号

php - PHP 引用如何在数组的底层工作?

php - 我可以在现有 PHP 应用程序中实现 Azure AD 身份验证吗

ios - 核心数据上下文更改导致崩溃

ios - 文档提供者不一致

javascript - JSON 破坏了我的脚本,但它仍然提取数据