GithubHelp home page GithubHelp logo

swiftyjson's Introduction

#SwiftyJSON SwiftyJSON makes it easy to deal with JSON data in Swift. ##Why is the typical JSON handling in Swift NOT good? Swift is very strict about types, it's good while explicit typing left us little chance to make mistakes. But while dealing with things that naturally implicit about types such as JSON, it's painful.

Take the Twitter API for example: say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline)

[
  {
    ......
    "text": "just another test",
    ......
    "user": {
      "name": "OAuth Dancer",
      "favourites_count": 7,
      "entities": {
        "url": {
          "urls": [
            {
              "expanded_url": null,
              "url": "http://bit.ly/oauth-dancer",
              "indices": [
                0,
                26
              ],
              "display_url": null
            }
          ]
        }
      ......
    },
    "in_reply_to_screen_name": null,
  },
  ......]
  

The code would look like this:

let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let statusesArray = jsonObject as? NSArray{
    if let aStatus = statusesArray[0] as? NSDictionary{
        if let user = aStatus["user"] as? NSDictionary{
            if let userName = user["name"] as? NSDictionary{
                //Finally We Got The Name
                
            }
        }
    }
}

It's not good.

Even if we use optional chaining, it would also cause a mess:

let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let userName = (((jsonObject as? NSArray)?[0] as? NSDictionary)?["user"] as? NSDictionary)?["name"]{
  //What A disaster above
}

An unreadable mess for something like this should really be simple!

##SwiftyJSON

With SwiftyJSON all you have to do is:

let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string{
  //Now you got your value
}

And don't worry about the Optional Wrapping thing, it's done for you automatically

let json = JSON(data: dataFromNetworking)
if let userName = json[999999]["wrong_key"]["wrong_name"].string{
    //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety
} else {
    //Print the error
    println(json[999999]["wrong_key"]["wrong_name"])
}

Requirements

  • iOS 7.0+ / Mac OS X 10.9+
  • Xcode 6.0

Usage

####Initialization

let json = JSON(data: dataFromNetworking)
let json = JSON(object: jsonObject)

####Use the optional getter

//NSNumber
if let id = json["user"]["favourites_count"].number {
   //Do something you want
} else {
   //Print the error
   println(json["user"]["favourites_count"])
}
//String
if let id = json["user"]["name"].string {
   //Do something you want
} else {
   //Print the error
   println(json["user"]["name"])
}
//Bool
if let id = json["user"]["is_translator"].bool {
   //Do something you want
} else {
   //Print the error
   println(json["user"]["is_translator"])
}
//Int
if let id = json["user"]["id"].integer {
   //Do something you want
} else {
   //Print the error
   println(json["user"]["id"])
}
...

####Use the non-optional getter (xxxValue)

//If not a Number or nil, return 0
let id: Int = json["id"].integerValue
//If not a String or nil, return ""
let name: String = json["name"].stringValue
//If not a Array or nil, return []
let list: Array<JSON> = json["list"].arrayValue
//If not a Dictionary or nil, return [:]
let user: Dictionary<String, JSON> = json["user"].dictionaryValue

###Get the raw object from JSON

let json = JSON(data: dataFromNetworking)
if let jsonObject: AnyObject = json.object {
   // do something
} else {
    // print the error
    println(json) 
}

##Integration

CocoaPods is not fully supported for Swift yet, to use this library in your project you should:

  1. for Projects just drag SwiftyJSON.swift to the project tree
  2. for Workspaces you may include the whole SwiftyJSON.xcodeproj as suggested by @garnett

##Work with Alamofire

To use Alamofire and SwiftyJSON, try Alamofire-SwiftyJSON.

swiftyjson's People

Contributors

lingoer avatar luketangpl avatar k06a avatar gregbarbosa avatar bkase avatar kriswallsmith avatar krishpop avatar yamada-wacul avatar

Watchers

James Cloos avatar Larry Martin avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.