JPMartha's Pancake

This blog is the way to brush up my poor English.

How to decode JSON having a nested data structure in Swift

Overview

This article describes how to decode JSON having a nested data structure with Himotoki.

Himotoki is a type-safe JSON decoding library purely written in Swift.

Motivation

  • A simple example is described on Himotoki's homepage.
  • I didn't used to understand how to decode JSON having a nested data structure with Himotoki.
  • Few reference are described that.

Example

The following example uses connpass API to request JSON.

The response JSON is the following:

{"results_returned": 10,
"results_available": 10,
"results_start": 1,
"events": [{
"event_id": 25185,
"title": "関西モバイルアプリ研究会 #10",

"event_id": 23958,
"title": "関西モバイルアプリ研究会 #9",

"event_id": 22648,
"title": "関西モバイルアプリ研究会 #8",

It has a nested data structure containing the following keys: event_id, title, …and so on.

First define the Event structure adopting the Decodable protocol.

public struct Event: Decodable {
    let event_id: Int
    let title: String
    
    public static func decode(e: Extractor) throws -> Event {
        return try Event(
            event_id: e <| "event_id",
            title: e <| "title"
        )
    }
}

Then define the ResponseField structure adopting the Decodable protocol.

The events property is an array of the Event structures.

struct ResponseField: Decodable {
    let results_returned: Int
    let results_available: Int
    let results_start: Int
    let events: [Event]
    
    static func decode(e: Extractor) throws -> ResponseField {
        return try ResponseField(
            results_returned: e <| "results_returned",
            results_available: e <| "results_available",
            results_start: e <| "results_start",
            events: e <|| "events"
        )
    }
}

Do the rest on your own. ?

Reference

github.com

www.slideshare.net