Swift4解码json模式中的字典
问题描述:
我试图解码一个json模式来表示它的内容在swift对象中。最后,该计划是生成swift模型文件。但是首先解码模式。Swift4解码json模式中的字典
我可以解码模式中的'属性'字典就好了。 但是,当我尝试解码属性中的'项'字典时,出现意外问题:
“预计解码字典,但找到了字符串/数据。
如果我注释掉行30 & 35以防止项目被解码,我会获得成功。 那么我的JSONSchema.properties结构与我的Property.items结构之间有什么区别?
我该在哪里出错?
我的代码:
import Foundation
enum ObjectType: String, Decodable {
case ObjectType = "object"
case ArrayType = "array"
case StringType = "string"
case IntegerType = "integer"
case NumberType = "number"
case BooleanType = "boolean"
case NullType = "null"
}
struct JSONSchema : Decodable {
let schema: String?
let id: String?
let properties: Dictionary<String, Property>?
enum CodingKeys : String, CodingKey {
case schema = "$schema"
case id
case properties
}
}
struct Property : Decodable {
let id: String?
let items: Dictionary<String, Item>?
let type: ObjectType?
enum CodingKeys : String, CodingKey {
case id
case items
case type
}
}
struct Item : Decodable {
let id: String?
// let properties: Dictionary<String, Property>?
// let type: ObjectType?
enum CodingKeys : String, CodingKey {
case id
// case properties
// case type
}
}
let jsonString = """
{
"$schema": "http://json-schema.org/draft-06/schema#",
"definitions": {},
"id": "http://example.com/example.json",
"properties": {
"cabinStatistics": {
"id": "/properties/cabinStatistics",
"items": {
"id": "/properties/cabinStatistics/items",
"properties": {
"cabinClass": {
"default": "C",
"description": "An explanation about the purpose of this instance.",
"examples": [
"C",
"M"
],
"id": "/properties/cabinStatistics/items/properties/cabinClass",
"title": "The cabinclass schema.",
"type": "string"
},
"count": {
"default": 29,
"description": "An explanation about the purpose of this instance.",
"examples": [
"29"
],
"id": "/properties/cabinStatistics/items/properties/count",
"title": "The count schema.",
"type": "integer"
},
"specificities": {
"id": "/properties/cabinStatistics/items/properties/specificities",
"items": {
"id": "/properties/cabinStatistics/items/properties/specificities/items",
"properties": {
"code": {
"default": "ACCEPTED",
"description": "An explanation about the purpose of this instance.",
"examples": [
"ACCEPTED"
],
"id": "/properties/cabinStatistics/items/properties/specificities/items/properties/code",
"title": "The code schema.",
"type": "string"
},
"count": {
"default": 21,
"description": "An explanation about the purpose of this instance.",
"examples": [
"21"
],
"id": "/properties/cabinStatistics/items/properties/specificities/items/properties/count",
"title": "The count schema.",
"type": "integer"
}
},
"type": "object"
},
"type": "array"
}
},
"type": "object"
},
"type": "array"
}},
"type": "object"
}
"""
if let jsonData = jsonString.data(using: .utf8) {
do {
let jsonSchema = try JSONDecoder().decode(JSONSchema.self, from: jsonData)
print(jsonSchema)
print("Success !!")
}
catch {
print(error)
print("Bummer ...")
}
}
答
一个JSON字典直接解码成结构
你需要写
struct Property : Decodable {
let id: String?
let items : Item?
let type: ObjectType?
...