自分自身を更新し、最新のSwift 4機能を使用しようとしています。Swift 4 - コーディング可能なプロトコル(ネストされたデータ)を使用したJSON解析
私はCodable
プロトコルでJSONを解析し、モデルオブジェクトを直接マップするためにトレーニングをしています。
まず、私はいくつかの研究と自己学習を行いました。
この記事では私をたくさん助けた:Ultimate guide
私はちょうど「COM」のアレイに焦点を当てる必要があります。
わかりますように、いくつかのネストされたオブジェクトが含まれています。私はそれらにFlash Infoという名前をつけた。
それはによって定義されますので、ここで
- endDateに
- テキスト
- 画像[]
- タイトル
- productionDate
- ID
は私のコード化可能な構造体であります:
struct FlashInfo : Codable {
let productionDate: String
let endDate: String
let text: String
let title: String
let id: String
}
まず、画像の配列なしで解析しようとしていましたが、後で処理します。私は唯一の方法私の配列を埋めるために、すべてのネストされたオブジェクトを反復処理する「COM」のアレイとを必要とするという事実を処理する方法がわからない
func getFlashInfo(success: @escaping (Array<FlashInfo>) -> Void) {
var arrayFlash = [FlashInfo]()
Alamofire.request(URL_TEST, method: .get).responseJSON { response in
if response.value != nil {
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}
//let decoder = JSONDecoder()
// let flash = try! decoder.decode(FlashInfo.self, from: response.data!)
// arrayFlash.append(flash)
success(arrayFlash)
} else {
print("error getFlashInfo")
}
}
}
:だからここ
は私の方法であり、コールバックで
つまり、デコードプロトコルはオブジェクトごとに反復処理されますか?
私はクリアですか?
EDIT:JSONテキスト
{"Test": [], "Toto": [], "Com": [{"endDate": "2017-06-27T08:00:00Z", "text": "John Snow is getting married", "image": ["895745-test.png", "632568-test.png"], "titre": "We need you!", "productionDate": "2017-07-02T16:16:23Z", "id": "9686"}, {"endDate": "2017-07-27T08:00:00Z", "text": "LOL TEST", "image": ["895545-test.png", "632568-test.png"], "titre": "She needs you!", "productionDate": "2017-08-02T16:16:23Z", "id": "9687"},{"endDate": "2017-06-27T08:00:00Z", "text": "iOS swift", "image": ["895775-test.png", "638568-test.png"], "titre": "They need you!", "productionDate": "2017-07-02T16:16:23Z", "id": "9688"}], "Yt": []}
jsonをテキストとして追加してください。 – RaffAl