Swift 可解码:检查是否存在嵌套结构

Swift decodable : check is a nested structure is present

我有一个 JSON 数据是这样的。我使用了一种单独的结构方法,而不是在一个单一的结构中使用嵌套键。需要注意的是,GivenJson中的key是不一致的,可能不存在。因此,在尝试使用构建结构解析每个键之前,必须对每个键进行检查。

 {  "ProductInfo": [
      {
        "productCode": "ABC",
        "productWeight": "2.3",
      }
    ],
    "ProductService": [
      {
        "serviceCode": "00",
        "serviceSite": 0
      }],

"ProductName": "StackSite"
}

为了解析这个我创建了 swift 像这样的结构

struct ProductStructure: Decodable{
var ProductInfo: productInfo
var ProductService: [productService]
var ProductName:String

enum ProductStructureKeys: String , CodingKey{
case ProductInfo
case ProductService
case ProductName

}

struct productInfo : Decodable {
   var productCode:String
   var productWeight:String
}

struct ProductService : Decodable {
    var serviceCode:String
    var serviceSite: Int
}


**// the decoder for the Main Structure**
extension ProductStructure{
  init(from decoder: Decoder) throws {

let container = try decoder.container(
      keyedBy: ProductStructureKeys.self)

//checks if product name key is present
 let product: String = try container.decodeIfPresent(String.self, forKey: . ProductName)


*//What code should I put here to check if my other two structures are present and parse them if they are present.* 

}

最简单的解决方案是将属性 productInfoproductService 声明为可选(名称以小写字母开头)。顺便说一下两个对象都是数组

struct ProductStructure: Decodable {
    let productInfo: [ProductInfo]?
    let productService: [ProductService]?
    let productName: String

    enum CodingKeys: String, CodingKey {
        case productInfo = "ProductInfo"
        case productService = "ProductService"
        case productName = "ProductName" 
    }

    struct ProductInfo : Decodable {
        let productCode: String
        let productWeight: String
    }

    struct ProductService : Decodable {
        let serviceCode: String
        let serviceSite: Int
    }
}

如果 ProductService 中的键 serviceCode 也可能丢失,请以与可选

相同的方式声明 属性
 let serviceCode: String?

不需要自定义初始化程序,假设 data 包含 JSON 作为 Data

let productStructure = try decoder.decode(ProductStructure.self, from: data)