Five simple steps to native model goodness:
You can install js2model from PyPI using pip, or clone the git repository from GitHub and run the setup.py script.
Clone the repository from github, install the dependencies, then run the setup.py script:
$ git clone git@github.com:thomsonreuters/js2model.git
$ cd js2model
$ pip install -r requirements.txt
$ python setup.py install
For purpose of this example, we’ll use the following JSON Schema. Let’s assume a file name of quickstart.schema.json.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "address",
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"county": { "type": "string" },
"state": { "type": "string" },
"zip": { "type": "string" }
}
}
If you do not already have a JSON Schema definition for your JSON, it can be tedious to create it. Fortunately you can automatically create schema files from JSON data using GenSON. GenSON (rhymes with Gen Con) is a powerful, user-friendly JSON Schema generator built in Python. See the docs for more details.
Run js2model to generate the model source files:
$ js2model -o output quickstart.schema.json
The command from the previous step will output the following files:
── output
├── TRModels.h
├── TRQuickstart.h
└── TRQuickstart.m
Add all of these files to your project.
For this simple example, one model was generated, resulting in three files - TRQuickstart.h, TRQuickstart.m, and TRModels.h.
TRModels.h is a convenience header that contains #includes for all of the generated model header files.
TRQuickstart.h is the header file containing the interface declaration for the TRQuickstart model.
TRQuickstart.m is the implementation file for the TRQuickstart model.
Notes
- Models are prefixed with “TR” by default. You can change the prefix string with the –prefix command line option.
- js2model uses NSJSONSerialization to parse JSON for Objective C.
Load some JSON data into a model:
NSError *error;
NSData *jsonData = [self getSomeJSONFromSomewhere];
TRQuickstart *model = [TRQuickstart quickstartWithJSONData:data error:&error];
if( !error ) {
NSLog(@"Street = %@", model.street);
}
Or load JSON from a file into a model:
NSError *error;
TRQuickstart *model = [TRQuickstart quickstartWithJSONFromFileNamed:@"mydata.json" error:&error];
if( !error ) {
NSLog(@"Street = %@", model.street);
}