GithubHelp home page GithubHelp logo

vadoff / json Goto Github PK

View Code? Open in Web Editor NEW

This project forked from soffes/json

0.0 1.0 0.0 25 KB

Micro framework for easily parsing JSON in Swift 3 with rich error messages in less than 100 lines of code

License: MIT License

Swift 96.41% Objective-C 3.59%

json's Introduction

JSON

Version Build Status Carthage compatible

Micro framework for easily parsing JSON in Swift 3 with rich error messages in less than 100 lines of code.

infomercial voice 🎙 Are you tried of parsing JSON and not knowing what went wrong? Do you find complicated frameworks with confusing custom operators a hassle? Are you constantly wishing this could be simpler? Well now it can be, with JSON! Enjoy the Simple™

Usage

Let's say we have a simple user struct:

struct User {
    let name: String
    let createdAt: Date
}

Deserializing Attributes

We can add JSON deserialization to this really easily:

extension User: JSONDeserializable {
    init(jsonRepresentation json: JSONDictionary) throws {
        name = try decode(json, key: "name")
        createdAt = try decode(json, key: "created_at")
    }
}

(JSONDictionary is simply a typealias for [String: Any].)

Notice that you don't have to specify types! This uses Swift generics and pattern matching so you don't have to worry about this. The interface for those decode functions look like this:

func decode<T>(_ dictionary: JSONDictionary, key: String) throws -> T
func decode(_ dictionary: JSONDictionary, key: String) throws -> Date

There's a specialized verion that returns a Date. You can supply your own functions for custom types if you wish.

Here's deserialization in action:

let dictionary = [
    "name": "Sam Soffes",
    "created_at": "2016-09-22T22:28:37+02:00"
]

let sam = try User(jsonRepresentation: dictionary)

You can also simply do the following since user is JSONDeserializable.

let sam: User = try decode(dictionary)

Optional Attributes

Decoding an optional attribute is easy:

struct Comment {
    let body: String
    let publishedAt: Date?
}

extension Comment {
    init(jsonRepresentation json: JSONDictionary) throws {
        body = try deocde(json, key: "body")

        // See how we use `try?` to just get `nil` if it fails to decode?
        // Easy as that!
        publishedAt = try? deocde(json, key: "published_at")
    }
}

Deserializing Nested Dictionaries

Working with nested models is easy. Let's say we have the following post model:

struct Post {
    let title: String
    let author: User
}

extension Post: JSONDeserializable {
    init(jsonRepresentation json: JSONDictionary) throws {
        title = try decode(json, key: "title")
        author = try decode(json, key: "author")
    }
}

We can simply treat a nested model like any other kind of attribute because there's a generic function constrainted to JSONDeserializable. Here's the annotated implementation:

public func decode<T: JSONDeserializable>(_ dictionary: JSONDictionary, key: String) throws -> T {
    // Decode the value like normal as a JSONDictionary. If this fails for whatever
    // reason, it will throw the appropriate errors.
    let value: JSONDictionary = try decode(dictionary, key: key)

    // Decode the model. This will call the initializer in the protocol for the
    // expected type. If decoding fails in the model, this will also throw the
    // appropriate erros.
    return try decode(value)
}

Deserializing Custom Types

Let's say you have the following enum:

enum RelationshipStatus: String {
    case stranger
    case friend
    case blocked
}

You could define a decode function for this type very easily:

func decode(_ dictionary: JSONDictionary, key: String) throws -> RelationshipStatus {
    let string: String = try decode(dictionary, key: key)

    guard let status = RelationshipStatus(rawValue: string) else {
        throw JSONDeserializationError.invalidAttribute(key: key)
    }

    return status
}

Then you can do try decode(dictionary, key: "status") like normal and it will throw the appropriate errors for you.

How cool is that‽

json's People

Contributors

soffes avatar

Watchers

 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.