可以解码Swift中可以和数组或单个元素的JSON数据吗? [英] Hot to decode JSON data that could and array or a single element in Swift?
问题描述
我有一个名为Info的结构,该结构根据接收到的数据进行解码.但有时,数据中的值之一可以是double或double数组.我该如何设置我的结构?
I have a struct named Info which is decoded based on the data it receives. But sometimes, one of the values in data can either be a double or an array of double. How do I set up my struct for that?
struct Info: Decodable {
let author: String
let title: String
let tags: [Tags]
let price: [Double]
enum Tags: String, Decodable {
case nonfiction
case biography
case fiction
}
}
根据网址,我要么获得双倍价格
Based on the url, I either get price as a double
{
"author" : "Mark A",
"title" : "The Great Deman",
"tags" : [
"nonfiction",
"biography"
],
"price" : "242"
}
或者我将其作为双打数组
or I get it as an array of doubles
{
"author" : "Mark A",
"title" : "The Great Deman",
"tags" : [
"nonfiction",
"biography"
],
"price" : [
"242",
"299",
"335"
]
}
我想设置我的结构,以便如果我收到一个double而不是一个double数组,则应该将price解码为1个double的数组.
I want to setup my struct so that if I receive a double instead of an array of doubles, price should be decoded as an array of 1 double.
推荐答案
您的JSON实际上是字符串或字符串数组.因此,您需要创建一个自定义解码器进行解码,然后将其转换为Double:
Your JSON actually is either a String or an array of Strings. So you need to create a custom decoder to decode and then convert them to Double:
struct Info {
let author, title: String
let tags: [Tags]
let price: [Double]
enum Tags: String, Codable {
case nonfiction, biography, fiction
}
}
extension Info: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
author = try container.decode(String.self, forKey: .author)
title = try container.decode(String.self, forKey: .title)
tags = try container.decode([Tags].self, forKey: .tags)
do {
price = try [Double(container.decode(String.self, forKey: .price)) ?? .zero]
} catch {
price = try container.decode([String].self, forKey: .price).compactMap(Double.init)
}
}
}
游乐场测试
Playground testing
let infoData = Data("""
{
"author" : "Mark A",
"title" : "The Great Deman",
"tags" : [
"nonfiction",
"biography"
],
"price" : "242"
}
""".utf8)
do {
let info = try JSONDecoder().decode(Info.self, from: infoData)
print("price",info.price) // "price [242.0]\n"
} catch {
print(error)
}
let infoData2 = Data("""
{
"author" : "Mark A",
"title" : "The Great Deman",
"tags" : [
"nonfiction",
"biography"
],
"price" : [
"242",
"299",
"335"
]
}
""".utf8)
do {
let info = try JSONDecoder().decode(Info.self, from: infoData2)
print("price",info.price) // "price [242.0, 299.0, 335.0]\n"
} catch {
print(error)
}
这篇关于可以解码Swift中可以和数组或单个元素的JSON数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!