A JBoss Project
Red Hat

Aerogear Guides Tutorials to help get you off and running.

AeroGear JsonSZ


AeroGear JsonSZ is our attempt to provide a convenient library to perform serialization of Swift objects to JSON and back. The library supports both one-to-one or one-to-many relationships between objects, encapsulated in either Array’s or Dictionaries.

Here is an example usage modeling of a Contact and a relationship with it’s Address:

class Contact : JSONSerializable {
    var first: String?
    var last: String?
    var addr: Address?

    required init() {}

    class func map(source: JsonSZ, object: Contact) {
        object.first <= source["first"]
        object.last <= source["last"]
        object.addr <= source["addr"]

class Address: JSONSerializable {

    var street: String?
    var poBox: Int?
    var city: String?
    var country: String?

    var arr:[String]

    required init() {}

    class func map(source: JsonSZ, object: Address) {
        object.street <= source["street"]
        object.poBox <= source["poBox"]
        object.city <= source["city"]
        object.country <= source["country"]

Shown by the example, it is required that objects implement the JSONSerializable protocol and the corresponding map method. The method is automatically called by the library when it is time to serialize to JSON and back. You simply have to specify the association between object instance variables and the corresponding JSON key (shown in quotes in the source object). And that’s it!

Let’s see now how we can convert the objects to JSON and back:

let address =  Address()      // [1]
address.street = "Street"
address.poBox = 100
address.city="New York"
address.country = "US"

let user = User()       // [2]
user.first = "John"
user.last = "Doe"
// assign Address to User
user.addr = address

// initialize serializer
let serializer = JsonSZ()      // [3]

// serialize ToJSON
let JSON = serializer.toJSON(user)  // [4]
// ..send json to server

// serialize fromJSON
let user = serializer.fromJSON(JSON, to:User.self)   // [5]

// user now should be initialized

After constructing the objects in [1] and [2] we initialize the JsonSZ library object and call it’s convenient methods toJSON() [4] and fromJSON() [5] to convert the object to JSON and back respectively. The methods accept the JSON in which it will attempt to serialize, as well as the model object.

And that’s it!

if the objects in the JSON response are encapsulated in a top-level Array container, you can use the convenient method fromJSONArray() instead.

Head over to our test-suite for more example usage of the API and give us feedback on the mailing list. We will love to hear your thoughts and suggestions!