如何使用新的可解码协议解码此JSON? 问题

如何使用新的可解码协议解码此JSON? 问题,json,swift,decodable,Json,Swift,Decodable,我试图解码JSON文件,以便将其转换为本机结构类型。显然它不起作用,我也不知道为什么。我复制了结构中的所有JSON对象,因此可解码协议可以完成它的工作 JSON文件 可以在此处找到JSON文件: 模型(结构) 这些模型反映了JSON文件中完全相同的对象 struct Appstructure: Decodable { var data: [Subdata] } struct Subdata: Decodable { var favourites: Items var cart:

我试图解码JSON文件,以便将其转换为本机结构类型。显然它不起作用,我也不知道为什么。我复制了结构中的所有JSON对象,因此可解码协议可以完成它的工作

JSON文件 可以在此处找到JSON文件:

模型(结构) 这些模型反映了JSON文件中完全相同的对象

 struct Appstructure: Decodable {
  var data: [Subdata]
}

struct Subdata: Decodable {
  var favourites: Items
  var cart: Items
}

struct Items: Decodable {
  var items: [Item]
}

struct Item: Decodable {
  var type: String
  var content: Content
}

struct Content: Decodable {
  var productLines: [String]
  var productImage: String
}
JSON解析 我使用苹果提供的JSONDecoder,如下所示:

func fetchAppStructure() -> Appstructure? {
    guard let path = Bundle.main.path(forResource: "iMessage-test-version-3", ofType: "json") else { return nil }

    guard let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: []) else { return nil }

    do {
      try JSONDecoder().decode(Appstructure.self, from: data)
    } catch  {
      print(error.localizedDescription)
    }

    return nil
  }
错误 但是,我收到以下解码错误

 DecodingError
  ▿ keyNotFound : 2 elements
    - .0 : CodingKeys(stringValue: "cart", intValue: nil)
    ▿ .1 : Context
      ▿ codingPath : 2 elements
        - 0 : CodingKeys(stringValue: "data", intValue: nil)
        ▿ 1 : _JSONKey(stringValue: "Index 0", intValue: 0)
          - stringValue : "Index 0"
          ▿ intValue : Optional<Int>
            - some : 0
      - debugDescription : "No value associated with key CodingKeys(stringValue: \"cart\", intValue: nil) (\"cart\")."
      - underlyingError : nil
DecodingError
▿ keyNotFound:2个元素
-.0:编码键(stringValue:“cart”,intValue:nil)
▿ .1:背景
▿ 编码路径:2个元素
-0:编码键(stringValue:“数据”,intValue:nil)
▿ 1:_JSONKey(stringValue:“索引0”,intValue:0)
-stringValue:“索引0”
▿ intValue:可选
-部分:0
-debugDescription:“没有与键编码键关联的值(stringValue:\“cart\”,intValue:nil)(“cart\”)
-参考误差:零
如果需要任何其他东西来复制此错误,请询问。这可能是逻辑思维上的小问题。希望有人能看到这个问题!提前谢谢


你的结构是错误的

子数据有
收藏夹
购物车
,而不是两者都有

使
收藏夹
购物车
可选

struct Subdata: Decodable {
  var favourites: Items?
  var cart: Items?
}

你有:
{“data”:[{“favorites”:{…},{“cart”:{…}]}
但是你的模型需要:
{“data”:[{“favorites”:{…},“cart”:{…}]}
(使用JSON“prettify”工具来更清楚地看到差异(并在使用它之前删除“…”)。你能用书面swift重现它吗?我正在尝试获取它。)你所做的一切都不一样。我已经有了你在回答中定义的结构。但是没有使用可选的。(唯一的区别)@KevinVugts,是的,对不起,我错了。我更新了答案。另一个建议-尽可能避免使用“数据”和“子数据”之类的名称。另外,jsonviewer.stack.hu对于检查json非常方便。