A simple library for parsing and serializing JSON to any Swift data structures. Complete style control with minimal changes.
Developed at KryptCo (https://krypt.co)
We recommend managing dependencies with git submodules.
git submodule add git@github.com:KryptCo/JSON.git
This library works with all Swift data structures (i.e Structs, Classes, and Enums).
To use with your data structures:
- JSON to Swift: implement JsonReadable.
- Swift to JSON: implement JsonWritable.
- Both: implement Jsonable
To convert data structures to JSON and back we do the following.
do{letcar=Car(make:"Toyota", model:"Rav4", year:"2004")
// Serialize to JSON data/string
letcarJson=try car.jsonString()
// Init object from JSON
letparsedCar=tryCar(jsonString: carJson)}catch{
// catch errors here
}To implement a struct that can be initialized from JSON or can be serialized to JSON we do the following.
structCar:Jsonable{varmake:Stringvarmodel:Stringvaryear:Int
// use the `~>` operator function
// to easily parse json into stored properties
// type inference makes the syntax simple
init(json:Object)throws{
make =try json ~>"make"
model =try json ~>"model"
year =try json ~>"year"}varobject:Object{return["make": make,"model": model,"year": year
]}}See more examples in
JSONTests/TestTypes.swift