ios - 结构体数组 - 可编码

标签 ios swift

请指导我找到可能的重复项,但在我的研究中我无法找到解决方案。

这是我尝试从 REST API 解码的 JSON 对象:

{
    "name": "Oak",

    "leaves":[
    {
        "id": "1A",
        "damaged": false
    },
    {
        "id": "2A",
        "damaged": false
    },
    {
        "id": "3E",
        "damaged": false
    }
]

}

这是到目前为止的代码:

struct Tree: Codable {
     var name : String?
     var leaves : [Leaf]?

     init() {
        self.name = string()
        self.leaves = []
     }
 }

struct Leaf: Codable {
     var id : String?
     var damaged : Bool?

     init(){
        self.id = String()
        self.damaged = Bool()
     }
}

现在,当我使用 API 时,我使用以下方法解码响应:

let jsonDecoder = JSONDecoder()
let time = try jsonDecoder.decode(Tree.self, from: data)

当我尝试解码此 API 时,我得到:

“无法读取数据,因为格式不正确。”

感谢您提供的任何指导,谢谢!

此外,init 的存在是因为它们用作单例,我不是在寻找不使用单例模式的建议,我只是想找出此解码的问题所在。

编辑:

感谢大家的回复!我以为问题出在自定义结构体的数组上,但实际上它更简单,我觉得很愚蠢。看看我下面的回答。

再次感谢大家的指导,让我谦卑下来!

最佳答案

对于任何在 swift4 数组中查看自定义结构这个问题的人来说,这段代码确实可以按预期工作。

当我提出问题时,我认为这不是问题,我的数据中遗漏了一个参数。附加字段现在位于下面,我的问题是我将日期声明为 Int32?而不是 Int64?。

{
    "name": "Oak",
    "discoveryDate": 1514178000000,

    "leaves":[
    {
        "id": "1A",
        "damaged": false
    },
    {
        "id": "2A",
        "damaged": false
    },
    {
        "id": "3E",
        "damaged": false
    }
]

}

这会将结构更改为:

struct Tree: Codable {
     var name : String?
     var discoveryDate : Int64?
     var leaves : [Leaf]?

     init() {
        self.name = String()
        self.discoveryDate = Int64()
        self.leaves = []
     }
 }

struct Leaf: Codable {
     var id : String?
     var damaged : Bool?

     init(){
        self.id = String()
        self.damaged = Bool()
     }
}

关于ios - 结构体数组 - 可编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47708270/

相关文章:

iOS:如何在没有 someView.addConstraints 的情况下使用 constraintsWithVisualFormat?

objective-c - 两个NSDate之间的日期比较

ios - 为什么我的 UIPasteboard 代码不起作用?

objective-c - 当数据不是静态时,我应该如何保存大量数据。 iOS、 cocoa touch 、Obj-C

swift - 为什么我们可以在Swift语言的类中使用 'static'?

ios - Facebook IOS SDK调用同步

iPhone 屏幕锁定后 iOS 套接字反复断开连接

swift - 创建可以使用图像作为填充的绘图应用程序的最佳方法

ios - moveRowAt IndexPath 在 Swift 2 中使用核心数据

facebook - 在 Swift 中链接/合并 Facebook 用户和 PFUser(解析)