我正在嘗試使用 swift codable 解碼 JSON,但是我在如何處理資料方面遇到了問題,尤其是因為結構是動態的,所以我使用了列舉來決議 JSON。
決議資料后,我嘗試使用陣列映射,但出現錯誤
這里是一個JSON樣本(如果你需要完整版本在這里 的網址):
{
"kind": "Listing",
"data": {
"after": null,
"dist": 1,
"modhash": "",
"geo_filter": "",
"children": [
{
"kind": "t1",
"data": {
"title": "Test",
"score": 88,
"replies": {
"kind": "Listing",
"data": {
"after": null,
"dist": null,
"modhash": "",
"geo_filter": "",
"children": [
{
"kind": "t1",
"data": {
"title": "Test",
"score": 88
}
},
{
"kind": "t1",
"data": {
"title": "post",
"score": 12
}
}
]
}
}
}
}
]
}
}
這是我決議 JSON 的方式
import Foundation
enum DataType : String, Decodable {
case listing = "Listing"
case t1
case t3
case more
}
indirect enum Parse : Decodable {
case listing(Listing)
case t1(Comment)
case t3(Comment)
case more(More)
enum CodingKeys : String, CodingKey {
case kind
case data
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let kind = try container.decode(DataType.self, forKey: .kind)
switch kind {
case .listing:
self = .listing(try container.decode(Listing.self, forKey: .data))
case .t1:
self = .t1(try container.decode(Comment.self, forKey: .data))
case .t3:
self = .t3(try container.decode(Comment.self, forKey: .data))
case .more:
self = .more(try container.decode(More.self, forKey: .data))
}
}
}
我正在使用一個模型,所以model.listings 應該包含在下面的代碼中決議的結果資料
let decoder = JSONDecoder()
var result = try decoder.decode([Parse].self, from: data!)
self.listings = result
在終端中,如果我 POmodel.listings資料存在
這是一個例子
? 2 elements
? 0 : Parse
? listing : Listing
? paginator : Paginator
? after : Optional<String>
- some : ""
? before : Optional<String>
- some : ""
? modhash : Optional<String>
- some : ""
? children : 1 element
? 0 : Parse
? t3 : Comment
? id : 51C7640E-D382-467B-9A65-6CAB04FA470E
- uuid : "51C7640E-D382-467B-9A65-6CAB04FA470E"
? title : Optional<String>
- some : "test"
? score : Optional<Int>
- some : 88
- replies : nil
我的問題是我不知道如何處理這些資料
我試過類似的東西:
var test = model.listings.map( { $0.listing } )
但它說“Enum case 'listing'不能用作實體成員”
也試過這種方式:
var test = model.listings.listing[0].children
在這種情況下,錯誤是:型別 '[Parse]' 的值沒有成員 'listing'
我剛開始使用 swift 所以我現在真的很困惑,處理這種資料的最佳方法是什么?
uj5u.com熱心網友回復:
嘗試使用以下機制之一:
// Using a Switch to enumerate the possibilities and using a pattern to extract the associated data
switch result {
case .listing(let aListing) :
print(aListing.geo_filter)
case .t1(let comment) :
print(comment.title)
case .t3(let comment) :
print(comment.title)
}
// Using a if case with a pattern to extract one particular enum case
if case .listing(let aListing) = result {
debugPrint(aListing)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343658.html
