Swift:解码 json 响应
Swift: Decode json response
我有一个后端响应,其格式为:
{
"Items": [
{
"Id": "blabla",
"Text": "blabla",
"Description": "blabla"
},
{
"Id": "blabla",
"Text": "blabla",
"Description": "blabla"
}]
}
直接解码数组的最佳Swift方法是什么?
目前我有一个响应结构,但我还必须考虑“Items”键,它对项目没有任何业务逻辑影响。
struct SearchResult: Decodable {
let Id: String
let Text: String
let Description: String
}
您的 JSON 缺少数组末尾的尾随 ]
。
除此之外,您只需要一个包装器即可为您提供 Items
数组。例如,这很好用:
let jsonData = """
{
"Items": [
{
"Id": "blabla",
"Text": "blabla",
"Description": "blabla"
},
{
"Id": "blabla",
"Text": "blabla",
"Description": "blabla"
}
]
}
""".data(using: .utf8)!
struct ResultWrapper: Decodable {
var Items : [SearchResult]
}
struct SearchResult: Decodable {
let Id: String
let Text: String
let Description: String
}
do {
let results = try JSONDecoder().decode(ResultWrapper.self, from: jsonData)
print(results.Items) //this is your array
} catch {
print(error)
}
我有一个后端响应,其格式为:
{
"Items": [
{
"Id": "blabla",
"Text": "blabla",
"Description": "blabla"
},
{
"Id": "blabla",
"Text": "blabla",
"Description": "blabla"
}]
}
直接解码数组的最佳Swift方法是什么?
目前我有一个响应结构,但我还必须考虑“Items”键,它对项目没有任何业务逻辑影响。
struct SearchResult: Decodable {
let Id: String
let Text: String
let Description: String
}
您的 JSON 缺少数组末尾的尾随 ]
。
除此之外,您只需要一个包装器即可为您提供 Items
数组。例如,这很好用:
let jsonData = """
{
"Items": [
{
"Id": "blabla",
"Text": "blabla",
"Description": "blabla"
},
{
"Id": "blabla",
"Text": "blabla",
"Description": "blabla"
}
]
}
""".data(using: .utf8)!
struct ResultWrapper: Decodable {
var Items : [SearchResult]
}
struct SearchResult: Decodable {
let Id: String
let Text: String
let Description: String
}
do {
let results = try JSONDecoder().decode(ResultWrapper.self, from: jsonData)
print(results.Items) //this is your array
} catch {
print(error)
}