我试图解码一个json模式来表示它在swift对象中的内容。最后,计划是生成swift模型文件。但首先解码模式。
我可以解码'属性'模式中的字典很好。 但是,当我尝试解码'项目'属性中的字典,我遇到了意想不到的问题:
"预计会解码字典,但会找到一个字符串/数据。"
如果我注释掉第30和30行。为了防止物品被解码,我获得了成功。 那么我的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 ...")
}
}
答案 0 :(得分:1)
JSON字典直接解码为struct
你需要写
struct Property : Decodable {
let id: String?
let items : Item?
let type: ObjectType?
...