1

I have a JSON data that goes something like this. I have used a separate structure approach rather than having nested keys for very structure in a single one. The point to be noted is that the keys in the Given Json are not consistent and may be absent. Hence a check has to be made for each key before trying to parse it with the built structure.

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

"ProductName": "StackSite"
}

to Parse this I have created swift structure like these

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.* 

}
4

1 に答える 1