json - 有没有办法在 Swift 中仅从 JSON 部分创建对象?

标签 json swift mapping partial

我正在创建一个 SwiftUI 抽认卡应用程序,使用 Codable 并遵循 Apple 用他们的 landmarks tutorial app 展示的技术我没有问题。用于导入 JSON 数据以创建其对象数组。

但是,我的抽认卡对象的两个属性不需要从 JSON 加载,如果我可以单独初始化这些值而不是从 JSON 加载它们,我可以最大限度地减少 JSON 文件中所需的文本。问题是我无法在没有错误的情况下加载 JSON 数据,除非它准确映射到对象的所有属性,即使缺少的属性是用值硬编码的。

这是我的对象模型:

import SwiftUI

class Flashcard: Codable, Identifiable {
    let id: Int
    var status: Int
    let chapter: Int
    let question: String
    let answer: String
    let reference: String
}

这是有效的 JSON:

[
  {
    "id": 1,
    "status": 0,
    "chapter": 1,
    "question": "This is the question",
    "answer": "This is the answer",
    "reference": "This is the reference"
  }
  //other card info repeated after with a comma separating each
]

与其在 JSON 中不必要地列出“id”和“status”,不如将模型更改为如下所示:

import SwiftUI

class Flashcard: Codable, Identifiable {
    let id = UUID()
    var status: Int = 0

    //only load these from JSON:
    let chapter: Int
    let question: String
    let answer: String
    let reference: String
}

...然后理论上我应该能够从 JSON 中删除“id”和“status”(但我不能)。有没有一种简单的方法可以防止 JSON 未完全映射到对象的错误?

最佳答案

是的,您可以通过在 Codable 类上设置编码键来实现。只需从 json 中删除您不想更新的内容即可。

class Flashcard: Codable, Identifiable {
    let id = UUID()
    var status: Int = 0
    let chapter: Int
    let question: String
    let answer: String
    let reference: String

    enum CodingKeys: String, CodingKey {
        case chapter, question, answer, reference
    }
}

HackingWithSwift 在 Codable 上有一篇很棒的文章 here

关于json - 有没有办法在 Swift 中仅从 JSON 部分创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58751701/

相关文章:

ios - 无法将 JSONValue 写入 NSDictionary - JSON 框架无法正常工作

android - 如何在 Django View 中处理 Web 和移动请求

ios - UIImagepicker 上传到错误的 Firebase 存储

mapping - 将 Web.SiteMap 与动态 URL(URL 路由)一起使用

mysql - 如何将openstreetmap数据放入我的mysql数据库中?

c# - AutoMapper: 'AutoMapper.AutoMapperMappingException' 类型的异常发生在 AutoMapper.dll 中,但未在用户代码中处理

javascript - 探索并获取多级对象的属性

javascript - Golang 后端到 javascript JSON Parse

swift - 错误 : Protocol requires a nested type '_BitsType' (Swift. 浮点类型)

arrays - (Index, value) Pairs while looping through a Array