我有一个类似这样的 JSON 数据。我使用了一种单独的结构方法,而不是在一个单独的结构中使用嵌套键。需要注意的一点是Given Json中的key不一致,可能不存在。因此,在尝试使用构建的结构解析它之前,必须对每个键进行检查。
{ "ProductInfo": [
{
"productCode": "ABC",
"productWeight": "2.3",
}
],
"ProductService": [
{
"serviceCode": "00",
"serviceSite": 0
}],
"ProductName": "StackSite"
}
解析这个我已经创建了像这样的快速结构
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.*
}