• Stars
    star
    354
  • Rank 120,042 (Top 3 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created about 10 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Convert JSON to Swift objects.

JSONJoy

Convert JSON to Swift objects. The Objective-C counterpart can be found here: JSONJoy.

Parsing JSON in Swift has be likened to a trip through Mordor, then JSONJoy would be using eagles for that trip.

Deprecation

The release of Swift 4 brought support for the new Codable protocol. This renders most of JSONJoy unneccessary and thus will be deprecated. Version 3.0.2 has been update to support Swift 4 as a means of backward compatibility, but I would encourage the adoption of the new Codable protocol. I wrote a post about it here

First thing is to import the framework. See the Installation instructions on how to add the framework to your project.

import JSONJoy

Example

First here is some example JSON we have to parse.

{
    "id" : 1,
    "first_name": "John",
    "last_name": "Smith",
    "age": 25,
    "address": {
        "id": 1,
        "street_address": "2nd Street",
        "city": "Bakersfield",
        "state": "CA",
        "postal_code": 93309
     }

}

We want to translate that JSON to these Swift objects:

struct Address {
    let objID: Int?
    let streetAddress: String?
    let city: String?
    let state: String?
    let postalCode: String?
    init() {

    }
}

struct User {
    let objID: Int?
    let firstName: String?
    let lastName: String?
    let age: Int?
    let address = Address()
    init() {

    }
}

Normally this would put us in a validation nightmare:

var user = User()
var error: NSError?
var response: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: &error)
if let userDict = response as? NSDictionary {
    if let addressDict = userDict["address"] as? NSDictionary {
        user.address.city = addressDict["city"] as? String
        user.address.streetAddress = addressDict["street_address"] as? String
        //etc, etc
    }
    user.firstName = userDict["first_name"] as? String
    user.lastName = userDict["last_name"] as? String
    //etc, etc
}

JSONJoy makes this much simpler. We have our Swift objects implement the JSONJoy protocol:

struct Address : JSONJoy {
    let objID: Int
    let streetAddress: String
    let city: String
    let state: String
    let postalCode: String
    let streetTwo: String?

    init(_ decoder: JSONLoader) throws {
        objID = try decoder["id"].get()
        streetAddress = try decoder["street_address"].get()
        city = try decoder["city"].get()
        state = try decoder["state"].get()
        postalCode = try decoder["postal_code"].get()
        streetTwo = decoder["street_two"].getOptional()
        
        //just an example of "checking" for a property. 
        if let meta: String = decoder["meta"].getOptional() {
            print("found some meta info: \(meta)")
        }
    }
}

struct User : JSONJoy {
    let objID: Int
    let firstName: String
    let lastName: String
    let age: Int
    let address: Address
    let addresses: [Address]

    init(_ decoder: JSONLoader) throws {
        objID = try decoder["id"].get()
        firstName = try decoder["first_name"].get()
        lastName = try decoder["last_name"].get()
        age = try decoder["age"].get()
        address = try Address(decoder["address"])
        addresses = try decoder["addresses"].get() //infers the type and returns a valid array
    }
}

Then when we get the JSON back:

do {
	var user = try User(JSONLoader(data))
	println("city is: \(user.address.city)")
	//That's it! The object has all the appropriate properties mapped.
} catch {
	print("unable to parse the JSON")
}

This also has automatic optional validation like most Swift JSON libraries.

//some randomly incorrect key. This will work fine and the property will just be nil.
firstName = decoder[5]["wrongKey"]["MoreWrong"].getOptional()
//firstName is nil, but no crashing!

Custom Types

If you to extend a standard Foundation type (you probably won't need to though)

extension UInt64:   JSONBasicType {}

SwiftHTTP

This can be combined with SwiftHTTP to make API interaction really clean and easy.

https://github.com/daltoniam/SwiftHTTP#clientserver-example

Requirements

JSONJoy requires at least iOS 7/OSX 10.10 or above.

Installation

Swift Package Manager

Add the project as a dependency to your Package.swift:

import PackageDescription

let package = Package(
    name: "YourProject",
    dependencies: [
        .Package(url: "https://github.com/daltoniam/JSONJoy-Swift", majorVersion: 3)
    ]
)

CocoaPods

Check out Get Started tab on cocoapods.org.

To use JSONJoy-Swift in your project add the following 'Podfile' to your project

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'JSONJoy-Swift', '~> 3.0.2'

Then run:

pod install

Carthage

Check out the Carthage docs on how to add a install. The JSONJoy framework is already setup with shared schemes.

Carthage Install

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate JSONJoy into your Xcode project using Carthage, specify it in your Cartfile:

github "daltoniam/JSONJoy-Swift" >= 3.0.2

Rogue

First see the installation docs for how to install Rogue.

To install JSONJoy run the command below in the directory you created the rogue file.

rogue add https://github.com/daltoniam/JSONJoy-Swift

Next open the libs folder and add the JSONJoy.xcodeproj to your Xcode project. Once that is complete, in your "Build Phases" add the JSONJoy.framework to your "Link Binary with Libraries" phase. Make sure to add the libs folder to your .gitignore file.

Other

Simply grab the framework (either via git submodule or another package manager).

Add the JSONJoy.xcodeproj to your Xcode project. Once that is complete, in your "Build Phases" add the JSONJoy.framework to your "Link Binary with Libraries" phase.

Add Copy Frameworks Phase

If you are running this in an OSX app or on a physical iOS device you will need to make sure you add the JSONJoy.framework included in your app bundle. To do this, in Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar. In the tab bar at the top of that window, open the "Build Phases" panel. Expand the "Link Binary with Libraries" group, and add JSONJoy.framework. Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add JSONJoy.framework.

TODOs

  • Add Unit Tests

License

JSONJoy is licensed under the Apache v2 License.

Contact

Dalton Cherry

More Repositories

1

Starscream

Websockets in swift for iOS and OSX
Swift
8,302
star
2

SwiftHTTP

Thin wrapper around NSURLSession in swift. Simplifies HTTP requests.
Swift
1,880
star
3

DCAnimationKit

A collection of animations for iOS. Simple, just add water animations.
Objective-C
801
star
4

Skeets

Fetch, cache, and display images via HTTP in Swift.
Swift
191
star
5

bumblebee

Abstract text processing and pattern matching engine in Swift. Converts text into NSAttributedStrings. Builtin markdown support.
Swift
109
star
6

tarkit

untar and tar files on iOS and OS X. Also supports gzip tars.
Objective-C
89
star
7

SwiftLog

Simple and easy logging in Swift.
Swift
72
star
8

UICustomizeKit

Base UIKit components extended to allow almost any customizations. Comes with Bootstrap and Flat UIs out of the box.
Objective-C
68
star
9

JSONJoy

Makes JSON a joy to use
Objective-C
56
star
10

FontAwesome-iOS

Provides easy access to font Awesome icons in iOS
Objective-C
46
star
11

DCLabel

Convert markdown or html text with embed content into a label.
Objective-C
31
star
12

DCCommentView

Comment view for iOS, same as messages app. Customizable.
Objective-C
30
star
13

Jazz

Easier layer animations in Swift
Swift
25
star
14

DCTextEngine

An engine that convert text to attributed strings and attributed strings to text. Supports HTML and markdown by default.
Objective-C
23
star
15

DCSideNav

Custom Navigation for iPad. Similar to iPad twitter app navigation.
Objective-C
17
star
16

DCDataViews

Simple and Powerful data management model for UITableView and UICollectionView to make simpler and faster to use.
Objective-C
10
star
17

GPLib-iOS

General Purpose iOS library
Objective-C
10
star
18

FeedView

A simple feed based view in Swift with customizable and delightful animations. Think UICollectionView with the animations you always wanted.
Swift
9
star
19

DCAvatar

A simple, asynchronous, network based avatar library for iOS and OSX
Objective-C
7
star
20

DCSlideOutViewController

Does the slide view thing as seen in Path app.
Objective-C
7
star
21

SimpleSwiftApp

Just a basic Swift App using SwiftHTTP and JSONJoy
Swift
6
star
22

DCXMPP

XMPP library for iOS or OSX in objective-c
Objective-C
5
star
23

XMLKit-objc

XML parsing in objective-C
Objective-C
2
star
24

Sideswipe

Network Image Library in Swift
Swift
2
star
25

common-crypto-spm

common crypto headers provided for the Swift Package Manager
Swift
2
star
26

bazaarvoice-challenge

Bazaarvoice programming exercise
Swift
1
star
27

goguid

generate GUID and UUIDs in go.
Go
1
star
28

daltoniam.com

portfolio website
CSS
1
star
29

bro

learn to write in a interpreter in C
C
1
star