Giter VIP home page Giter VIP logo

json's Introduction

JSON

Version Build Status Swift Version Carthage compatible

Micro framework for easily parsing JSON in Swift 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(json: JSON) throws {
        name = try json.decode(key: "name")
        createdAt = try json.decode(key: "created_at")
    }
}

(JSON 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: JSONDeserializable>(key: String) throws -> T
func decode<T: JSONDeserializable>(key: String) throws -> [T]
func decode(key: String) throws -> Date
func decode(key: String) throws -> URL

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 json = [
    "name": "Sam Soffes",
    "created_at": "2016-09-22T22:28:37+02:00"
]

let sam = try User(json: json)

Optional Attributes

Decoding an optional attribute is easy:

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

extension Comment {
    init(json: JSON) throws {
        body = try json.decode(key: "body")

        // See how we use `try?` to just get `nil` if it fails to decode?
        // Easy as that!
        publishedAt = try? json.decode(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(json: JSONDictionary) throws {
        title = try json.decode(key: "title")
        author = try json.decode(key: "author")
    }
}

We can simply treat a nested model like any other kind of attribute because there’s a generic function constrainted to JSONDeserializable and User in our example conforms to that.

Deserializing Enums

Enums that are RawRepresentable, meaning they have an underlying type and no associated values, will deserialize with any additional work! Let’s say we have the following enum:

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

We could simply deserialize it like this assuming our User example earlier now has a property for it:

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

extension User: JSONDeserializable {
    init(json: JSON) throws {
        name = try json.decode(key: "name")
        createdAt = try json.decode(key: "created_at")
        relationshipStatus = try json.decode("relationship_status")
    }
}

If your enum isn’t RawRepresentable, see the next section for providing a custom decode method for it.

Deserializing Custom Types

You can also define custom decode function for custom types very easily. We’ll use TimeZone as an example:

extension Dictionary where Key : StringProtocol {
    func decode(key: Key) throws -> TimeZone {
        // Get the JSON representation of it. Here, it’s a string.
        let string: String = try decode(key: key)

        // Initialize TimeZone with the identifier you decoded already.
        guard let timeZone = TimeZone(identifier: string) else {
            throw JSONDeserializationError.invalidAttribute(key: String(key))
        }

        return timeZone
    }
}

Then you can do try json.decode(key: "timezone") like normal and it will throw the appropriate errors for you or decode a valid TimeZone value.

How cool is that‽

json's People

Contributors

soffes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json's Issues

Provide a default decode for RawRepresentable type

👋 I was wondering if there was interest in me adding a default decode function for RawRepresentable types?

An example of what I'm using in my own project:

func decode<T: RawRepresentable>(_ dictionary: JSONDictionary, key: String) throws -> T {
    let object: Any = try decode(dictionary, key: key)
    
    guard let rawValue = object as? T.RawValue else {
        throw JSONDeserializationError.invalidAttributeType(key: key, expectedType: T.self, receivedValue: object)
    }
    
    guard let value = T(rawValue: rawValue) else {
       // Ideally represented by a new error case called `.invalidRawValue(key: key, rawValue: rawValue)`
        throw JSONDeserializationError.invalidAttribute(key: key)
    }
    
    return value
}

If there's interest, I can add the code, add a specific error case, update the readme, and add tests 😄 .

Regardless, thanks for the project. It's been a pleasure to work with.

Automatically decode key paths?

Would it make sense for this project to add the ability to decode key paths? I wanted to discuss it first before making a PR. Or maybe someone has a better implementation.

Given the json
{"error":{"code":401, "message":"unauthorized"}}

Then get the code with
let statusCode: Int = try decode(json, key: "error.code")

Something like this:

/// Generically decode an value from a given JSON dictionary.
///
/// - parameter dictionary: a JSON dictionary
/// - parameter key: key in the dictionary
/// - returns: The expected value
/// - throws: JSONDeserializationError
public func decode<T>(_ dictionary: JSONDictionary, key: String) throws -> T {
    
    // decode key paths in the format of "first.second.third"
    if key.contains(".") {
        var keys = key.components(separatedBy: ".")
        let firstKey = keys.removeFirst()
        guard let second = dictionary[firstKey] as? JSONDictionary else {
            throw JSONDeserializationError.invalidAttribute(key: firstKey)
        }
        return try decode(second, key: keys.joined(separator: "."))
    }
    
    guard let value = dictionary[key] else {
        throw JSONDeserializationError.missingAttribute(key: key)
    }
    
    guard let attribute = value as? T else {
        throw JSONDeserializationError.invalidAttributeType(key: key, expectedType: T.self, receivedValue: value)
    }
    
    return attribute
}

Installation Section

Hey, your library is really interesting.

The only problem I found was the README.md, which lacks an Installation Section
I created this iOS Open source Readme Template so you can take a look on how to easily create an Installation Section
If you want, I can help you to organize the README.

What are your thoughts? 😄

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.