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!