我有一个类似这样的JSON数据。我使用了单独的结构方法,而不是在单个结构中使用嵌套键。需要注意的是,给定Json中的键不一致,可能不存在。因此,在尝试使用构建的结构解析之前,必须对每个键进行检查。
{ "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.*
}
答案 0 :(得分:1)
最简单的解决方案是将属性productInfo
和productService
声明为可选(并且名称以小写字母开头)。顺便说一句两个对象都是数组
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
}
}
如果serviceCode
中的键ProductService
也可能丢失,请以与可选
let serviceCode: String?
不需要自定义初始值设定项,假设data
包含JSON为Data
let productStructure = try decoder.decode(ProductStructure.self, from: data)