我正在嘗試解碼來自 Pinboard API 的所有標簽的 JSON 回應。我有一個簡單的模型,我想解碼為:
struct Tag: Coddle, Hashable {
let name: String
let count: Int
}
問題是我得到的 JSON 回應是完全動態的,如下所示:
{
"tag_name_1": 5,
"tag_name_2": 5,
"tag_name_3": 5,
}
所以使用解碼到我的模型JSONDecoder.decode([Tag].self, data)總是失敗。
uj5u.com熱心網友回復:
您的 JSON 可以解碼為型別的字典[String: Int]。
如果將字典中每個條目的鍵和值輸入到Tag物件中,則可以按 對標簽陣列進行排序name。或者您可以先對字典鍵進行排序,兩者都可以。
Catch:只有當 JSON 的順序也是鍵的順序時,它才會起作用。如果 JSON 像這樣到達,它將不遵循順序,例如:
{
"tag_name_3": 5,
"tag_name_2": 5,
"tag_name_1": 5,
}
這是代碼(有兩個選項):
// First way:
// 1) Decode the dictionary
// 2) Sort the dictionary keys
// 3) Iterate, creating a new Tag and appending it to the array
private func decode1() {
let json = "{ \"tag_name_1\": 5, \"tag_name_2\": 5, \"tag_name_3\": 5}"
let data = json.data(using: .utf8)
do {
// Decode into a dictionary
let decoded = try JSONDecoder().decode([String: Int].self, from: data!)
print(decoded.sorted { $0.key < $1.key })
var tags = [Tag]()
// Iterate over a sorted array of keys
decoded.compactMap { $0.key }.sorted().forEach {
// Create the Tag
tags.append(Tag(name: $0, count: decoded[$0] ?? 0))
}
print(tags)
} catch {
print("Oops: something went wrong while decoding, \(error.localizedDescription)")
}
}
// Second way:
// 1) Decode the dictionary
// 2) Create the Tag objects
// 3) Sort the array by Tag.name
private func decode2() {
let json = "{ \"tag_name_1\": 5, \"tag_name_2\": 5, \"tag_name_3\": 5}"
let data = json.data(using: .utf8)
do {
// Decode into a dictionary
let decoded = try JSONDecoder().decode([String: Int].self, from: data!)
print(decoded.sorted { $0.key < $1.key })
var tags = [Tag]()
// Iterate over the dictionary entries
decoded.forEach {
// Create the Tag
tags.append(Tag(name: $0.key, count: $0.value))
}
// Sort the array by name
tags = tags.sorted { $0.name < $1.name }
print(tags)
} catch {
print("Oops: something went wrong while decoding, \(error.localizedDescription)")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471662.html
標籤:迅速
上一篇:將資料過濾到帶有部分的串列中
