使用 Swift 解码包含不同类型的字典的 JSON



我有一个JSON格式,我试图用JSONDecoder解析,但由于JSON的结构方式,我不知道该怎么做。

这是 JSON 的格式。为了简洁起见,我将省略一些内容。

{
"name":"John Smith",
"addresses":[
{
"home":{
"street":"123 Main St",
"state":"CA"
}
},
{
"work":{
"street":"345 Oak St",
"state":"CA"
}
},
{
"favorites":[
{
"street":"456 Green St.",
"state":"CA"
},
{
"street":"987 Tambor Rd",
"state":"CA"
}
]
}
]
}    

我不知道如何定义一个可解码的结构,然后我可以解码。addresses是字典的数组。homework分别包含一个地址,而favorites包含一个地址数组。我无法将地址定义为[Dictionary<String, Address],因为favorites是一个地址数组。我无法将其定义为[Dictionary<String, Any>]因为这样我就会收到Type 'UserProfile' does not conform to protocol 'Encodeable'错误。

有人知道我如何解析它吗?如何解析值根据键而变化的字典?

谢谢。

我假设你的JSON是这样的:

{
"name": "John Smith",
"addresses": [
{
"home": {
"street": "123 Main St",
"state": "CA"
}
},
{
"work": {
"street": "345 Oak St",
"state": "CA"
}
},
{
"favorites": [
{
"street": "456 Green St.",
"state": "CA"
},
{
"street": "987 Tambor Rd",
"state": "CA"
}
]
}
]
}

我必须进行一些更改才能成为有效的 JSON。

可以使用以下结构始终将地址属性映射到[[String: [Address]]]

struct Response: Decodable {
let name: String
let addresses: [[String: [Address]]]

enum CodingKeys: String, CodingKey {
case name
case addresses
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)

name = try container.decode(String.self, forKey: .name)
var unkeyedContainer = try container.nestedUnkeyedContainer(forKey: .addresses)
var addresses = [[String: [Address]]]()
while !unkeyedContainer.isAtEnd {
do {
let sindleAddress = try unkeyedContainer.decode([String: Address].self)
addresses.append(sindleAddress.mapValues { [$0] } )
} catch DecodingError.typeMismatch {
addresses.append(try unkeyedContainer.decode([String: [Address]].self))
}
}
self.addresses = addresses
}
}
struct Address: Decodable {
let street: String
let state: String
}

基本上,在init(from:)的自定义实现中,我们尝试将addresses属性解码为[String: Address],如果成功,则创建[String: [Address]]类型的新字典,其中值数组中只有一个元素。如果失败,那么我们将addresses属性解码为[String: [Address]].

更新:我更愿意添加另一个结构:

struct AddressType {
let label: String
let addressList: [Address]
}

并将Responseaddresses属性修改为[AddressType]

struct Response: Decodable {
let name: String
let addresses: [AddressType]

enum CodingKeys: String, CodingKey {
case name
case addresses
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)

name = try container.decode(String.self, forKey: .name)
var unkeyedContainer = try container.nestedUnkeyedContainer(forKey: .addresses)
var addresses = [AddressType]()
while !unkeyedContainer.isAtEnd {
let addressTypes: [AddressType]
do {
addressTypes = try unkeyedContainer.decode([String: Address].self).map {
AddressType(label: $0.key, addressList: [$0.value])
}
} catch DecodingError.typeMismatch {
addressTypes = try unkeyedContainer.decode([String: [Address]].self).map {
AddressType(label: $0.key, addressList: $0.value)
}
}
addresses.append(contentsOf: addressTypes)
}
self.addresses = addresses
}
}

一个可能的解决方案,使用enum,可能是工作,家庭或收藏夹:

struct Top: Decodable {

let name: String
let addresses: [AddressType]

enum CodingKeys: String, CodingKey {
case name
case addresses
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.addresses = try container.decode([AddressType].self, forKey: .addresses)
}
}
enum AddressType: Decodable {

case home(Address)
case work(Address)
case favorites([Address])

enum CodingKeys: String, CodingKey {
case home
case work
case favorites
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let home = try container.decodeIfPresent(Address.self, forKey: .home) {
self = AddressType.home(home)
} else if let work = try container.decodeIfPresent(Address.self, forKey: .work) {
self = AddressType.work(work)
} else {
let favorites = try container.decodeIfPresent([Address].self, forKey: .favorites)
self = AddressType.favorites(favorites ?? [])
}
}
}
struct Address: Decodable {
let street: String
let state: String
}

测试(我猜是对您的 JSON 进行修复):

let jsonStr = """
{
"name": "John Smith",
"addresses": [{
"home": {
"street": "123 Main St",
"state": "CA"
}
}, {
"work": {
"street": "345 Oak St",
"state": "CA"
}
}, {
"favorites": [{
"street": "456 Green St.",
"state": "CA"
}, {
"street": "987 Tambor Rd",
"state": "CA"
}]
}]
}
"""
let jsonData = jsonStr.data(using: .utf8)!
do {
let top = try JSONDecoder().decode(Top.self, from: jsonData)

print("Top.name: (top.name)")
top.addresses.forEach {
switch $0 {
case .home(let address):
print("It's a home address:nt(address)")
case .work(let address):
print("It's a work address:nt(address)")
case .favorites(let addresses):
print("It's a favorites addresses:")
addresses.forEach{ aSubAddress in
print("t(aSubAddress)")
}
}
}
} catch {
print("Error: (error)")
}

输出:

$>Top.name: John Smith
$>It's a home address:
Address(street: "123 Main St", state: "CA")
$>It's a work address:
Address(street: "345 Oak St", state: "CA")
$>It's a favorites addresses:
Address(street: "456 Green St.", state: "CA")
Address(street: "987 Tambor Rd", state: "CA")

注意: 之后,您应该能够根据需要在Top上设置惰性变量:

lazy var homeAddress: Address? = {
return self.addresses.compactMap {
if case AddressType.home(let address) = $0 {
return address
}
return nil
}.first
}()

相关内容

  • 没有找到相关文章

最新更新