【问题标题】:Couldn't parse Json name with UUID()无法使用 UUID() 解析 Json 名称
【发布时间】:2019-10-28 15:02:05
【问题描述】:

我有下一个解析模型

struct Unicards: Hashable, Codable, Identifiable {
var id: String?
var title: String?
var info: String?
var brand: String?
var model: String?
var make_year: Int?
var message: String?
var message_color: String?

我有一个 Json 文件,其中有许多具有不同数据集的重复数组,但具有相同的标头,有时是重复的 ID

我想用

var uuid = UUID() 

为每个数据集生成一个唯一ID,并使用唯一ID函数

list (model, id: \ .uuid)

但是当我添加这一行时,我得到一个错误

   "Thread 1: Fatal error: Couldn't parse" Json name ""

我做错了什么,请告诉我

我已经浏览了很多答案,但我不明白我的错误到底是什么。

试过

var uuid: UUID = UUID ()

var uuid = UUID (). uuidString

【问题讨论】:

    标签: model uuid swiftui codable swift5


    【解决方案1】:

    您出错的原因是,通过确认Codable 协议,它会尝试合成值,并且当您添加一个不存在的值时,解码器会感到困惑。要解决这个问题,您需要做的就是将 CodingKeys 枚举添加到您的结构中。

    struct Unicards: Hashable, Codable, Identifiable {
    
        var uuid: UUID = UUID()
    
        var id: String?
        var title: String?
        var info: String?
        var brand: String?
        var model: String?
        var make_year: Int?           // by convention this should be makeYear
        var message: String?
        var message_color: String?    // by convention this should be messageColor
    
        enum CodingKeys: String, CodingKey {
            case id
            case title
            case info
            case brand
            case model
            case message
            case make_year
            case message_color
    
            // if you use the usual naming convention, you could swap these out
            // case makeYear = "make_year",
            // case messageColor = "message_color"
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-07
      • 2017-05-30
      • 2020-05-01
      • 2016-06-23
      • 1970-01-01
      • 2022-12-11
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多