json2swift: a peek under the hood

This article presents a high-level overview of how my json2swift tool works.

Several people have expressed interest in using my code as the foundation for a similar tool, or just want to change the Swift code it generates, and have asked for guidance on how to get started. It’s a modest sized program, so this overview will be straightforward.

Here is a map of the pipeline in which JSON is transformed into Swift.


The user specifies a JSON file, represented by the top box in the diagram, when running json2swift on the command line. The JSON file data is read into memory and Apple’s JSONSerialization class tries to convert it into arrays, dictionaries, NSNumber‘s, etc.

Now things get interesting. The JSON objects are analyzed, using a process known as type inference, to create schemas which describe the JSON data entities. The data types that represent a JSON schema are defined here.

Analyzing a JSON document to infer its schema is handled here. However, one of the most useful aspects of json2swift is that it can combine evidence from multiple examples of an attribute, which I refer to as ‘attribute merging’ and have implemented here. An example of this functionality is shown in the Type Inference section of the repository’s README.

At this point the program has done nothing related to Swift whatsoever. If you want to use my JSON type inference engine for a different tool that generates code for languages other than Swift, there won’t be anything Swift-specific getting in your way.

The next step is to translate JSON schemas to data structures that represent the Swift code generated later on. Those abstractions of Swift types are defined in this file. Most of the translation logic is in here.

Last but not least the Swift model is used as a data source for SwiftCodeGenerator, as seen here. This is where you can tweak the tool’s generated Swift code. Once the Swift source code is generated, the tool writes it to a file with a .swift extension in the same directory as the input JSON file.

That’s all folks!

This entry was posted in Swift. Bookmark the permalink.

1 Response to json2swift: a peek under the hood

  1. Pingback: Dew Drop - November 14, 2016 (#2364) - Morning Dew

Comments are closed.