首页 > 解决方案 > How to decode this JSON with the new decodable protocol?

问题描述

Problem

I tried to decode my JSON file so it will be casted to native struct types. Apparently it does not work and I have no idea why. I replicated all the JSON objects in structs so the decodable protocol can do its work.

The JSON File

The JSON file can be found here: https://pastebin.com/hZxmDMue

The models (structs)

These are the models that reflect the exact same objects in the JSON file.

 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
}

The JSON Parsing

I am using the provided JSONDecoder by apple like so:

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
  }

Error

However I receive the following decoding error.

 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

If anything else is needed to reproduce this bug please ask. It is probably something small in logical thinking. Hopefully somebody sees the issue! Thanks in advance.

标签: jsonswiftdecodable

解决方案


你的结构是错误的。

子数据有一个favouritescart,而不是两者。

在此处输入图像描述

制作favouritescart可选。

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

推荐阅读