• Stars
    star
    602
  • Rank 74,409 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 4 years ago

Reviews

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

Repository Details

Hassle-free JSON encoding and decoding in Swift

Logo

Platform Language CocoaPods Carthage Travis CI License

#JSONCodable Hassle-free JSON encoding and decoding in Swift

Installation

  • Simply add the following to your Cartfile and run carthage update:
github "matthewcheok/JSONCodable" ~> 3.0.1
  • or add the following to your Podfile and run pod install:
pod 'JSONCodable', '~> 3.0.1'
  • or clone as a git submodule,

  • or just copy files in the JSONCodable folder into your project.

TLDR

  • Uses Protocol Extensions
  • Error Handling
  • Supports let properties
  • Supports enum properties backed by compatible values

Change Log

  • Moved encoding and decoding methods to a helper class

JSONCodable is made of two separate protocols JSONEncodable and JSONDecodable.

  • JSONEncodable allows your structs and classes to generate NSDictionary or [String: AnyObject] equivalents for use with NSJSONSerialization.

  • JSONDecodable allows you to generate structs from NSDictionary coming in from a network request for example.

##Decoding JSON Take these two types for example:

 struct User {    
     let id: Int    
     let name: String   
     var email: String?   
     var company: Company?    
     var friends: [User] = []   
 }    
    
 struct Company {   
     let name: String   
     var address: String?   
 }    

You'd simply add conformance to JSONDecodable (or to JSONCodable):

extension User: JSONDecodable {
  init(object: JSONObject) throws {
      let decoder = JSONDecoder(object: object)        
      id = try decoder.decode("id")
      name = try decoder.decode("full_name")
      email = try decoder.decode("email")
      company = try decoder.decode("company")
      friends = try decoder.decode("friends")
  }
}

extension Company: JSONDecodable {
  init(object: JSONObject) throws {
      let decoder = JSONDecoder(object: object)
      name = try decoder.decode("name")
      address = try decoder.decode("address")
  }
}

Note on Class Extensions: After the update to Swift 2.2 adding an initializer in an extension for classes is no longer supported. The current suggested work around for this is to just add the initializer in the class definition. For structs extensions still work as that had previously in this case.

Then provide the implementations for init(object: JSONObject) throws where JSONObject is a typealias for [String:AnyObject]. As before, you can use this to configure the mapping between keys in the Dictionary to properties in your structs and classes.

let user = try User(object: JSON)
print("\(user)")

Result:

User(
  id: 24,
  name: "John Appleseed",
  email: Optional("[email protected]"),
  company: Optional(Company(
    name: "Apple",
    address: Optional("1 Infinite Loop, Cupertino, CA")
  )),
  friends: [
    User(
      id: 27,
      name: "Bob Jefferson",
      email: nil,
      company: nil,
      friends: []
    ),
    User(
      id: 29,
      name: "Jen Jackson",
      email: nil,
      company: nil,
      friends: []
    )
  ]
)

Decoding Nested Arrays and Dictionary

Decoding also supports retrieving values using . separators for dictionaries and [index] for arrays. See below example:

name = try decoder.decode("value[0].properties.name")

Encoding JSON

Simply add conformance to JSONEncodable (or to JSONCodable):

extension User: JSONEncodable {
    func toJSON() throws -> Any {
        return try JSONEncoder.create({ (encoder) -> Void in
            try encoder.encode(id, key: "id")
            try encoder.encode(name, key: "full_name")
            try encoder.encode(email, key: "email")
            try encoder.encode(company, key: "company")
            try encoder.encode(friends, key: "friends")
        })
    }
}

extension Company: JSONEncodable {}

The default implementation of func toJSON() inspects the properties of your type using reflection (see Company.) If you need a different mapping, you can provide your own implementation (see User.)

Instantiate your struct, then use the func toJSON() method to obtain a equivalent form suitable for use with NSJSONSerialization:

let dict = try user.toJSON()
print("dict: \(dict)")

Result:

[full_name: John Appleseed, id: 24, email: john@appleseed.com, company: {
    address = "1 Infinite Loop, Cupertino, CA";
    name = Apple;
}, friends: (
        {
        friends =         (
        );
        "full_name" = "Bob Jefferson";
        id = 27;
    },
        {
        friends =         (
        );
        "full_name" = "Jen Jackson";
        id = 29;
    }
)]

Working with JSON Strings

The convenience initializer init?(JSONString: String) is provided on JSONDecodable. You may also use func toJSONString() throws -> String to obtain a string equivalent of your types.

Transforming values

To transform values, create an instance of JSONTransformer:

let JSONTransformerStringToNSURL = JSONTransformer<String, NSURL>(
        decoding: {NSURL(string: $0)},
        encoding: {$0.absoluteString})

A JSONTransformer converts between 2 types, in this case, String and NSURL. It takes a closure for decoding and another for encoding, and in each case, you return an optional value of the corresponding type given an input type (you can return nil if a transformation is not possible).

Next, use the overloaded versions of func encode() and func decode() to supply the transformer:

struct User {
  ...
  var website: NSURL?
}

init(object: JSONObject) throws {
    ...
    website = try JSONDictionary.decode("website", transformer: JSONTransformerStringToNSURL)
}

func toJSON() throws -> AnyObject {
    return try JSONEncoder.create({ (encoder) -> Void in
        ...
        try result.encode(website, key: "website", transformer: JSONTransformerStringToNSURL)
    })
}

The following transformers are provided by default:

  • JSONTransformers.StringToNSURL: String <-> NSURL
  • JSONTransformers.StringToNSDate: String <-> NSDate ISO format

Feel free to suggest more!

Extending JSONCodable (thanks to @raylillywhite)

This allows for JSONDecoder extensions that allow the type system to better aid in decoding. For example, you could do:

extension JSONDecoder {
    public func decode(key: String) throws -> NSURL {
        return try decode(key, transformer: JSONTransformers.StringToNSURL)
    }
}

then you only need to do:

try url = decoder.decode("url")

instead of

try url = decoder.decode("url", JSONTransformers.StringToNSURL)

Example code

Refer to the included playground in the workspace for more details.

License

JSONCodable is under the MIT license.

More Repositories

1

POP-MCAnimate

Concise syntax for the Pop animation framework.
Objective-C
951
star
2

Realm-JSON

A concise Mantle-like way of working with Realm and JSON.
Objective-C
663
star
3

MCPanelViewController

Drop-in panel control for iOS with blurring background and screen-edge activation gestures.
Objective-C
325
star
4

Fluent

Swift animation made easy
Swift
300
star
5

MCFireworksButton

Drop-in button control with with particle effects similar to the Like button in Facebook Paper.
Objective-C
233
star
6

Kaleidoscope

Writing a lexer and parser for Kaleidoscope in Swift
Swift
61
star
7

MCBlurredModalController

A sleek way to display your view controller modally.
Objective-C
61
star
8

Brotli

An iOS and OSX wrapper for Google's Brotli project.
C
47
star
9

MCNumberLabel

Drop-in label control with the ability to animate digits.
Objective-C
42
star
10

MCGraphView

A light-weight solution for displaying graphs.
Objective-C
19
star
11

MCNotificationManager

Show your own banners like Notification Center within your app.
Objective-C
17
star
12

MCModalView

UIAlertView/UIActionSheet replacement supporting iPhone/iPad and device rotations.
Objective-C
13
star
13

MCAppRouter

URL routing for iOS made simple.
Objective-C
10
star
14

Layout

Functional layout in Swift
Swift
9
star
15

MCBinaryHeap

An Objective-C wrapper of CFBinaryHeap. Core Foundation priority queue implementation.
Objective-C
9
star
16

MCDynamicObject

Automatic persistence for your next iOS project.
C
8
star
17

MCAdditions

A host of useful utilties for any iOS application.
Objective-C
6
star
18

MCObservation

Easy-to-use, fire-and-forget KVO and notifications.
Objective-C
5
star
19

MCTimeSeriesView

A light-weight solution for displaying time series charts.
Objective-C
5
star
20

JSONSerialization

Natively implemented JSON serialization in Swift
Swift
4
star
21

react-rebels

Flux simplified
JavaScript
2
star
22

polymorphism-with-protocols

Good API design is essential for writing code that scales. In this talk, we look at some characteristics of good design and how to refactor code using the protocol features in Swift.
Swift
2
star
23

react-kit

Boilerplate for project with React and Webpack.
JavaScript
2
star
24

amigo

Swift
1
star
25

Click

Easy window recording for macOS
Swift
1
star