---
title: "#283: Generating Models from JSON with json2swift ⚒"
url: https://littlebitesofcocoa.com/283-generating-models-from-json-with-json2swift
author: Jake Marsh
published: 2016-11-02
topics: ["Tools"]
description: "Integrating our apps with HTTP APIs often involves a fair amount of \"busy work\". Writing models to match API responses, manually iterating each field in a..."
---

# #283: Generating Models from JSON with json2swift ⚒

By Jake Marsh, November 2, 2016. HTML: https://littlebitesofcocoa.com/283-generating-models-from-json-with-json2swift

Integrating our apps with **HTTP APIs** often involves a fair amount of "busy work". Writing **models** to match **API responses**, manually iterating each **field** in a **JSON object**, and typing each in as a **Swift property** can be a bummer. Today we'll check out a great new tool from [Josh Smith](https://github.com/ijoshsmith) called [json2swift](https://github.com/ijoshsmith/json2swift) that can help us here. It can generate **Swift model** code from a **JSON** object. Let's give it a try.

After we've installed [json2swift](https://github.com/ijoshsmith/json2swift), we can run it like this:

``` bash
json2swift Spaceship.json
```

This will create a new file called `Spaceship.swift` in the same directory as our `.json`.

This means if our `Spaceship.json` file looked like this:

``` json
{
  "name": "Tantive IV",
  "topSpeed": 950
}
```

The resulting [json2swift](https://github.com/ijoshsmith/json2swift)-generated Swift model would look like this:

``` swift
struct RootType: CreatableFromJSON {
  let name: String
  let topSpeed: Int
}
```

Neat!

[json2swift](https://github.com/ijoshsmith/json2swift) has generated an immutable Swift struct from our **JSON** file. **Pro Tip:** We can also run this on a **directory** full of **JSON files**, and it will process all of them.

[json2swift](https://github.com/ijoshsmith/json2swift) will even try to determine which properties should be optional, and which are required. It will then generate the appropriate `init` code. 

We're even provided some special handling for things like **Date** parsing. If we put a special **String** like this in our original **JSON**:

``` json
{
  "name" : "Tantive IV".
  "buildDate" : "DATE_FORMAT=yyyy-MM-dd"
}
```

This will give us a:

``` swift
let buildDate: Date
```

**property**, as well as generate the appropriate **Date** format/parsing code needed to make it work. Neat! 

We've only scratched the surface, [json2swift](https://github.com/ijoshsmith/json2swift) has great support for intelligenty inferring types for things like numbers, and even URLs. Learn more about [json2swift](https://github.com/ijoshsmith/json2swift) at [git.io/json2swift](http://git.io/json2swift).
