terra incognita

JSON2Mantle:Generate Mantle models using JSON file

2015-03-11 00:59

Mantle is a model framework for Cocoa and Cocoa Touch. However, it is still needed to put each field name in a JSON file into the Mantle model files. To stay lazy, I wrote a tool to generate Mantle models by xxx.json file in Python.

Here it is: https://github.com/sutar/JSON2Mantle


$ sudo pip install JSON2Mantle


Converts property names automatically

(Semi) type detection

Preliminarily, it is possible to deal with primitive tpes, such as NSIntegerNSStringBOOL. Detecting types like NSURL is to be done.

Nested JSON object

Consider the following user object:

  "id": 10,
  "name": "Clementina DuBuque",
  "username": "Moriah.Stanton",
  "email": "Rey.Padberg@karina.biz",
  "address": {
    "street": "Kattie Turnpike",
    "suite_number": "Suite 198",
    "city": "Lebsackbury",
    "zipcode": "31428-2261",
    "geo": {
      "lat": "-38.2386",
      "lng": "57.2232"
  "cell_phone": "024-648-3804",
  "website": "ambrose.net",
  "company": {
    "name": "Hoeger LLC",
    "catch_phrase": "Centralized empowering task-force",
    "bs": "target end-to-end models"

Execute JSON2Mantle one and only once, four models, namely UserModel AddressModel GeoModel and CompanyModel will be generated.

The content of UserModel.h is:

#import <Mantle.h>
#import "AddressModel.h"
#import "CompanyModel.h"

@interface UserModel : MTLModel <MTLJSONSerializing>

@property (nonatomic, copy) NSString *username;
@property (nonatomic, copy) NSString *website;
@property (nonatomic, copy) NSString *email;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger modelId;
@property (nonatomic, strong) AddressModel *address;
@property (nonatomic, strong) CompanyModel *company;
@property (nonatomic, copy) NSString *cellPhone;


Yes, the only thing you need to do is:

$ json2mantle user.json output

That's it. Feel free to check it out at: https://github.com/sutar/JSON2Mantle

Pull requests are welcome.