使用 JSONDecoder 解码 Swift
Decode using JSONDecoder Swift
下面json对应的数据模型是什么?
{
dog:
{
type: "dog",
logoLocation: "url1"
},
pitbull:
{
type: "pitbull",
logoLocation: "url2"
}
}
这是字典中的字典
所以我试过了,
class PhotosCollectionModel: Codable {
var photoDictionary: Dictionary<String, PhotoModel>?
}
class PhotoModel: Codable {
var type: String?
var logoLocation: String?
}
但它不起作用。有什么帮助吗?
你需要
struct Root: Codable {
let dog, pitbull: Dog
}
struct Dog: Codable {
let type, logoLocation: String // or let logoLocation:URL
}
正确json
{
"dog":
{
"type": "dog",
"logoLocation": "url1"
},
"pitbull":
{
"type": "pitbull",
"logoLocation": "url2"
}
}
动态
只需在解码器
中使用[String:Dog]
do {
let res = try JSONDecoder().decode([String:Dog].self,from:data)
}
catch {
print(error)
}
我会跳过第一个 class 并保留
class PhotoModel: Codable {
var type: String
var logoLocation: String
}
然后像字典一样解码它
do {
let decoder = JSONDecoder()
let result = try decoder.decode([String: PhotoModel].self, from: data)
result.forEach { (key,value) in
print("Type: \(value.type), logo: \(value.logoLocation) (key: \(key))")
}
} catch {
print(error)
}
产出
Type: dog, logo: url1 (key: dog)
Type: pitbull, logo: url2 (key: pitbull)
这两个属性真的都是可选的吗,如果不是,我建议您删除 PhotoModel
中不必要的 ?
(我删除了)
下面json对应的数据模型是什么?
{
dog:
{
type: "dog",
logoLocation: "url1"
},
pitbull:
{
type: "pitbull",
logoLocation: "url2"
}
}
这是字典中的字典 所以我试过了,
class PhotosCollectionModel: Codable {
var photoDictionary: Dictionary<String, PhotoModel>?
}
class PhotoModel: Codable {
var type: String?
var logoLocation: String?
}
但它不起作用。有什么帮助吗?
你需要
struct Root: Codable {
let dog, pitbull: Dog
}
struct Dog: Codable {
let type, logoLocation: String // or let logoLocation:URL
}
正确json
{
"dog":
{
"type": "dog",
"logoLocation": "url1"
},
"pitbull":
{
"type": "pitbull",
"logoLocation": "url2"
}
}
动态
只需在解码器
中使用[String:Dog]
do {
let res = try JSONDecoder().decode([String:Dog].self,from:data)
}
catch {
print(error)
}
我会跳过第一个 class 并保留
class PhotoModel: Codable {
var type: String
var logoLocation: String
}
然后像字典一样解码它
do {
let decoder = JSONDecoder()
let result = try decoder.decode([String: PhotoModel].self, from: data)
result.forEach { (key,value) in
print("Type: \(value.type), logo: \(value.logoLocation) (key: \(key))")
}
} catch {
print(error)
}
产出
Type: dog, logo: url1 (key: dog)
Type: pitbull, logo: url2 (key: pitbull)
这两个属性真的都是可选的吗,如果不是,我建议您删除 PhotoModel
中不必要的 ?
(我删除了)