you520t / JSONHelper

Lightning fast JSON deserialization and value conversion library for iOS & OS X written in Swift.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

#JSONHelper CocoaPods CocoaPods

Build Status CocoaPods Stories in Ready Gratipay ![Gitter](https://badges.gitter.im/JOIN CHAT.svg)

Lightning fast JSON deserialization for iOS & OS X written in Swift.

##Table of Contents

  1. Introduction
  2. Installation
  3. Operator List
  4. Simple Tutorial
  5. Assigning Default Values
  6. NSDate and NSURL Deserialization
  7. JSON String Deserialization

##Introduction

JSONHelper is a library written to make sure that deserializing data obtained from an API is as easy as possible. It doesn't depend on any networking libraries, and works equally well with any of them.

Requires iOS 7 or later and Xcode 6.1+

##Installation

###Carthage

Add the following line to your Cartfile.

github "isair/JSONHelper"

Then do carthage update. After that, add the framework to your project.

###Cocoapods

Add the following line in your Podfile.

pod "JSONHelper"

###Drag & Drop

You can also add JSONHelper.swift directly into your project.

##Basic Tutorial

First of all I'm going to assume you use AFNetworking as your networking library; for simplicity. Let's say we have an endpoint at http://yoursite.com/movies/ which gives the following response when a simple GET request is sent to it.

{
  "movies": [
    {
      "name": "Filth",
      "release_date": "2014-05-30",
      "cast": {
        "Bruce": "James McAvoy",
        "Lennox": "Jamie Bell"
      }
    },
    {
      "name": "American Psycho",
      "release_date": "2000-04-14",
      "cast": {
        "Patrick Bateman": "Christian Bale",
        "Timothy Bryce": "Justin Theroux"
      }
    }
  ]
}

From this response it is clear that we have a book model similar to the implementation below.

struct Movie {
  var name: String?
  var releaseDate: NSDate?
  var cast: [String: String]?
}

We now have to make it extend the protocol Deserializable and implement the required init(data: [String: AnyObject]) initializer and use our deserialization operator (<--) in it. The complete model should look like this:

struct Movie: Deserializable {
  var name: String? // You can also use let instead of var if you want.
  var releaseDate: NSDate?
  var cast: [String: String]?

  init(data: [String: AnyObject]) {
    name <-- data["name"]
    releaseDate <-- (data["release_date"], "yyyy-MM-dd") // Refer to the next section for more info.
    cast <-- data["cast"]
  }
}

And finally, requesting and deserializing the response from our endpoint becomes as easy as the following piece of code.

AFHTTPRequestOperationManager().GET(
  "http://yoursite.com/movies/"
  parameters: nil,
  success: { operation, data in
    var movies: [Movie]?
    movies <-- data["movies"]
    
    if let movies = movies {
      // Response contained a movies array, and we deserialized it. Do what you want here.
    } else {
      // Server gave us a response but there was no "movies" key in it, so the movies variable
      // is equal to nil. Do some error handling here.
    }
  },
  failure: { operation, error in
    // Handle error.
})

##Assigning Default Values

You can easily assign default values to variables in cases where you want them to have a certain value when deserialization fails.

struct User: Deserializable {
  var name = "Guest"
  
  init(data: [String: AnyObject]) {
    name <-- data["name"]
  }
}

##NSDate and NSURL Deserialization

NSURL deserialization works very much like a primitive type deserialization.

let website: NSURL?
let imageURLs: [NSURL]?

website <-- "http://mywebsite.com"
imageURLs <-- ["http://mywebsite.com/image.png", "http://mywebsite.com/anotherImage.png"]

NSDate deserialization however, requires a format to be provided most of the time.

let meetingDate: NSDate?
let partyDates: [NSDate]?

meetingDate <-- ("2014-09-18", "yyyy-MM-dd")
partyDates <-- (["2014-09-19", "2014-09-20"], "yyyy-MM-dd")

let myDayOff: NSDate?
myDayOff <-- 1414172803 // You can also use unix timestamps.

##JSON String Deserialization

You can deserialize instances and arrays of instances directly from a JSON string as well. Here is a quick example.

struct Person: Deserializable {
  var name = ""

  init(data: [String: AnyObject]) {
    name <-- data["name"]
  }
}

let jsonString = "[{\"name\": \"Rocket Raccoon\"}, {\"name\": \"Groot\"}]"
var people = [Person]()

people <-- jsonString

for person in people {
  println(person.name)
}

About

Lightning fast JSON deserialization and value conversion library for iOS & OS X written in Swift.

License:Other


Languages

Language:Swift 95.7%Language:Ruby 2.4%Language:C++ 1.9%