قالب وردپرس درنا توس
Home / IOS Development / # 283: Generate JSON models with json2swift ⚒ – Little Bites of Cocoa

# 283: Generate JSON models with json2swift ⚒ – Little Bites of Cocoa



Issue

Topics

Integrating our apps with HTTP APIs often involve a lot of "busy work". Writing Models to match API Response manually iterate each field into a JSON object and type each as a ] Swift property can be a bummer. Today we are going to check out a great new tool from Josh Smith called json2swift who can help us here. It can generate Swift Model code from an JSON item. Let's try it.

After we have installed json2swift, we can run it like this:

  json2swift Spaceship.json

This will create a new file called Spaceship.swift in the same directory as our .json .

This means that if our Spaceship.json file looked like this: [1

9659000]
[name:
}
[19659000] The resulting json2swift generated Swift model looks like this:

  struct    RootType :    CreatableFromJSON    {
    la    name  :    String 
    la    TopSpeed ​​:    Int 
} 

Neat!

json2swift has generated an unchangeable 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 will even try to determine which features should be optional and which ones are required. It will then generate the correct init code.

We have provided some special handling for things like Date parsing. If we add a special String like this in our original JSON :

  {
    "Name"   :    "Tantive . 
    "buildDate"   :    "DATE_FORMAT = yyyy-MM-dd"  
}  
   [19659000] This will give us a: 

  la    buildDate :    Date 

property and generate the current Date format / parsing code needed to make it work. Tidy!

We only have the scratch surface, json2swift has great support for intelligent inferring types for things like numbers and even URLs. Learn more about json2swift at git.io/json2swift.


Source link