All Projects → soffes → Json

soffes / Json

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

Programming Languages

swift
15916 projects

Projects that are alternatives of or similar to Json

Dots
Lightweight Concurrent Networking Framework
Stars: ✭ 35 (-91.14%)
Mutual labels:  tvos, watchos, carthage
BlockiesSwift
Unique blocky identicons generator for Swift
Stars: ✭ 53 (-86.58%)
Mutual labels:  tvos, watchos, carthage
Mechanica
A cross-platform library of Swift utils to ease your iOS | macOS | watchOS | tvOS and Linux development.
Stars: ✭ 27 (-93.16%)
Mutual labels:  tvos, watchos, carthage
X
Easier cross platform Mac & iOS development with Swift
Stars: ✭ 270 (-31.65%)
Mutual labels:  tvos, watchos, carthage
clevertap-ios-sdk
CleverTap iOS SDK
Stars: ✭ 39 (-90.13%)
Mutual labels:  tvos, watchos, carthage
Iso8601
ISO8601 date parser and writer
Stars: ✭ 213 (-46.08%)
Mutual labels:  tvos, watchos, carthage
Web3.swift
A pure swift Ethereum Web3 library
Stars: ✭ 295 (-25.32%)
Mutual labels:  tvos, watchos, carthage
Cdmarkdownkit
An extensive Swift framework providing simple and customizable markdown parsing.
Stars: ✭ 158 (-60%)
Mutual labels:  tvos, watchos, carthage
Crypto
Swift CommonCrypto wrapper
Stars: ✭ 328 (-16.96%)
Mutual labels:  tvos, watchos, carthage
SwiftVer
Easily Manage Versioning in MacOS, iOS, watchOS, and tvOS projects.
Stars: ✭ 23 (-94.18%)
Mutual labels:  tvos, watchos, carthage
Cache
Swift caching library
Stars: ✭ 210 (-46.84%)
Mutual labels:  tvos, watchos, carthage
Xcglogger
A debug log framework for use in Swift projects. Allows you to log details to the console (and optionally a file), just like you would have with NSLog() or print(), but with additional information, such as the date, function name, filename and line number.
Stars: ✭ 3,710 (+839.24%)
Mutual labels:  tvos, watchos, carthage
L10n Swift
Localization of the application with ability to change language "on the fly" and support for plural form in any language.
Stars: ✭ 177 (-55.19%)
Mutual labels:  tvos, watchos, carthage
Lift
Lift is a Swift library for generating and extracting values into and out of JSON-like data structures.
Stars: ✭ 33 (-91.65%)
Mutual labels:  json, tvos, watchos
Cocoalumberjack
A fast & simple, yet powerful & flexible logging framework for Mac and iOS
Stars: ✭ 12,584 (+3085.82%)
Mutual labels:  tvos, watchos, carthage
Columbus
A feature-rich country picker for iOS, tvOS and watchOS.
Stars: ✭ 23 (-94.18%)
Mutual labels:  tvos, watchos, carthage
Ducttape
📦 KeyPath dynamicMemberLookup based syntax sugar for Swift.
Stars: ✭ 138 (-65.06%)
Mutual labels:  tvos, watchos, carthage
Color
Color utilities for macOS, iOS, tvOS, and watchOS
Stars: ✭ 145 (-63.29%)
Mutual labels:  tvos, watchos, carthage
TermiNetwork
🌏 A zero-dependency networking solution for building modern and secure iOS, watchOS, macOS and tvOS applications.
Stars: ✭ 80 (-79.75%)
Mutual labels:  tvos, watchos, carthage
Datez
📆 Breeze through Date, DateComponents, and TimeInterval with Swift!
Stars: ✭ 254 (-35.7%)
Mutual labels:  tvos, watchos, carthage

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‽

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].