ylliX - Online Advertising Network Parsing JSON with Swift 4 JSONDecoder - Yet Another Programmer's Blog

Parsing JSON with Swift 4 JSONDecoder

Probably you saw many JSON parsing examples, but this one is really easy. And available out of the box with Swift 4.
All you have to do is create models from Codable superclass, and use:

let decoder = JSONDecoder();
let myData = try! decoder.decode(MyModel.self, from: data!)

Check out provided playground here!

Output in console should be:

Colors:
Color(color: "black", category: "hue", type: "primary")
Color(color: "white", category: "value", type: "primary")
Color(color: "red", category: "hue", type: "primary")
Color(color: "blue", category: "hue", type: "primary")
Color(color: "yellow", category: "hue", type: "primary")
Color(color: "green", category: "hue", type: "secondary")

Leave a Reply