An extremely simple JSON helper written in Swift.

Related tags

JSON alexander
Overview

Alexander

Carthage Compatible CocoaPods Compatible

Alexander is an extremely simple JSON helper written in Swift. It brings type safety and Foundation helpers to the cumbersome task of JSON unpacking.

Requirements

Xcode Swift iOS tvOS OS X
10.2 5.0 8.0 9.0 10.9

Installation

Carthage

github "hodinkee/alexander"

CocoaPods

pod 'Alexander'

Usage

DecoderType

Make a new DecoderType that can unpack your object.

struct User {
    var ID: String
    var name: String
    var email: String
}

struct UserDecoder: DecoderType {
    typealias Value = User
    static func decode(JSON: Alexander.JSON) -> Value? {
        guard
            let ID = JSON["id"]?.stringValue,
            let name = JSON["name"]?.stringValue,
            let email = JSON["email"]?.stringValue
        else {
            return nil
        }
        return User(ID: ID, name: name, email: email)
    }
}

Now you can do let author = JSON["user"]?.decode(UserDecoder) to get a single user, or let users = JSON["users"]?.decodeArray(UserDecoder) to get an array of users.

You can make DecodableTypes for all kinds of things.

struct SizeDecoder {
    typealias Value = CGSize
    static func decode(JSON: Alexander.JSON) -> Value? {
        guard
            let width = JSON["width"]?.doubleValue,
            let height = JSON["height"]?.doubleValue
        else {
            return nil
        }
        return CGSize(width: width, height: height)
    }
}

Alexander ships with a handful of decoders for common types:

  • DateTimeIntervalSince1970Decoder
  • DateTimeIntervalSinceReferenceDateDecoder
  • URLDecoder
  • RawRepresentableDecoder

Nested Objects

Most of Alexander's power comes from its two subscript operators: subscript[key: String] -> JSON? and subscript[index: Int] -> JSON?. These operators allow you to unpack nested objects without having to refer to each intermediate step by hand. Something like let nextCursor = JSON["meta"]?["pagination"]?["next_cursor"]?.stringValue is a single line of code.

Enums & RawRepresentable

You can also decode anything that conforms to the RawRepresentable type. For example, assume the following enum:

enum Planet: String {
    case Mercury = "mercury"
    case Venus = "venus"
    case Earth = "earth"
    case Mars = "mars"
    case Jupiter = "jupiter"
    case Saturn = "saturn"
    case Uranus = "uranus"
    case Neptune = "neptune"
    // case Pluto = "pluto" =(
}

Because Planet is backed by a String raw value type, it is inheriently RawRepresentable. This means you can do let planet = JSON["planet"]?.decode(RawRepresentableDecoder<Planet>) or let planets = JSON["planets"]?.decodeArray(RawRepresentableDecoder<Planet>).

Comments
  • 1.2

    1.2

    • Add data() function that can render JSON data from the contained object
    • Reduce instances where multiple loops through an array or dictionary could happen
    • Better decodeArray function
    opened by calebd 3
  • Can not use parser with classes

    Can not use parser with classes

    Hello. Just try use swift 2 branch for project, that depend on realm, so i can not use struct with models.

    Here model looks like:

    import RealmSwift
    import Alexander
    
    class NewsItem: Object, JSONDecodable {
        dynamic var sid = 0
        dynamic var title = ""
    
        required init( sid: Int, title: String ) {
            super.init()
            self.sid = sid
            self.title = title
        }
    
        required init() {
            super.init()
        }
    
        static func decode(JSON: Alexander.JSON) -> Self? {
    
            if
                let sid = JSON["id"]?.int,
                let title = JSON["title"]?.string {
                    return NewsItem(sid: sid, title: title)
            }
            return nil
        }
    }
    

    I am still not familiar with swift, but looks similar to example code in readme.

    Therefore i have error

    compiler error

    Cannot convert return expression of type 'NewsItem' to expected return type 'Self'

    opened by roma86 1
  • Correct the spelling of CocoaPods in README

    Correct the spelling of CocoaPods in README

    This pull requests corrects the spelling of CocoaPods 🤓 https://github.com/CocoaPods/shared_resources/tree/master/media

    opened by ReadmeCritic 0
  • Alexander + RawRepresentable = ❤️

    Alexander + RawRepresentable = ❤️

    This PR adds some new functionality:

    • Adds generic decode<T>(transform: JSON -> T) -T? function.
      • This allows users to decode something that might not be JSONDecodable.
    • Adds decode<T: JSONDecodable>(type: T.Type) -> T? function.
      • This builds on the previous function addition to help clean up code paths such as let author = JSON["author"]?.decode(Author).
    • Adds decode<T: RawRepresentable>(type: T.Type) -> T?
      • Allows a user to decode JSON into a single enum instance.
    • Adds decodeArray<T: RawRepresentable>(type: T.Type) -> [T]?
      • Works like its JSONDecodable sibling, allows you to decode an array of enums.
    opened by cocoahero 0
  • 2.0 API

    2.0 API

    I'd like to clean up the API and release a 2.0.

    • [x] Switch from things like string and bool properties that use common type names to stringValue and boolValue
    • [x] Remove property getters for types that are not core JSON types
    • [x] Switch to new DecoderType and deprecate JSONDecodable
    • [x] Switch to new EncoderType and deprecate JSONEncodable
    • [x] Add arrayValue and dictionaryValue properties that expose the raw object as [AnyObject]? and [String: AnyObject] respectively
    opened by calebd 0
Releases(v5.0.0)
Owner
HODINKEE
HODINKEE
Swift-json - High-performance json parsing in swift

json 0.1.4 swift-json is a pure-Swift JSON parsing library designed for high-per

kelvin 43 Dec 15, 2022
JSON-Practice - JSON Practice With Swift

JSON Practice Vista creada con: Programmatic + AutoLayout Breve explicación de l

Vanesa Giselle Korbenfeld 0 Oct 29, 2021
Ss-json - High-performance json parsing in swift

json 0.1.1 swift-json is a pure-Swift JSON parsing library designed for high-per

kelvin 43 Dec 15, 2022
Swift parser for JSON Feed — a new format similar to RSS and Atom but in JSON.

JSONFeed Swift parser for JSON Feed — a new format similar to RSS and Atom but in JSON. For more information about this new feed format visit: https:/

Toto Tvalavadze 31 Nov 22, 2021
JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very important part of Pitaya.

John Lui 454 Oct 30, 2022
Simple JSON Object mapping written in Swift

ObjectMapper ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from J

Tristan Himmelman 9k Jan 2, 2023
HandyJSON is a framework written in Swift which to make converting model objects to and from JSON easy on iOS.

HandyJSON To deal with crash on iOS 14 beta4 please try version 5.0.3-beta HandyJSON is a framework written in Swift which to make converting model ob

Alibaba 4.1k Dec 29, 2022
Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift.

Himotoki Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift. This library is highly inspired by the popular Swift JSON parsin

IKEDA Sho 799 Dec 6, 2022
JASON is a faster JSON deserializer written in Swift.

JASON is a faster JSON deserializer written in Swift. JASON is the best framework we found to manage JSON at Swapcard. This is by far the fastest and

Damien 1k Oct 15, 2022
ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects to and from JSON.

ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from J

Tristan Himmelman 9k Jan 2, 2023
A type-safe JSON-RPC 2.0 library purely written in Swift

JSONRPCKit JSONRPCKit is a type-safe JSON-RPC 2.0 library purely written in Swift. // Generating request JSON let batchFactory = BatchFactory(version:

Shinichiro Oba 178 Mar 18, 2022
An iOS framework for creating JSON-based models. Written in Swift.

An iOS framework for creating JSON-based models. Written in Swift (because it totally rules!) Requirements iOS 8.0+ Xcode 7.3 Swift 2.2 Installation E

Oven Bits 448 Nov 8, 2022
A JSON parser with concise API written in Swift.

A JSON parser with concise API written in Swift Maps JSON attributes to different Swift types with just two methods: map and mapArrayOfObjects. The li

Evgenii Neumerzhitckii 14 Aug 13, 2018
Elevate is a JSON parsing framework that leverages Swift to make parsing simple, reliable and composable

Elevate is a JSON parsing framework that leverages Swift to make parsing simple, reliable and composable. Elevate should no longer be used for

Nike Inc. 611 Oct 23, 2022
Codable code is a Swift Package that allows you to convert JSON Strings into Swift structs

Codable code is a Swift Package that allows you to convert JSON Strings into Swift structs.

Julio Cesar Guzman Villanueva 2 Oct 6, 2022
Implement dynamic JSON decoding within the constraints of Swift's sound type system by working on top of Swift's Codable implementations.

DynamicCodableKit DynamicCodableKit helps you to implement dynamic JSON decoding within the constraints of Swift's sound type system by working on top

SwiftyLab 15 Oct 16, 2022
AlamofireObjectMappe - An Alamofire extension which converts JSON response data into swift objects using ObjectMapper

AlamofireObjectMapper An extension to Alamofire which automatically converts JSON response data into swift objects using ObjectMapper. Usage Given a U

Tristan Himmelman 2.6k Dec 29, 2022
Freddy - A reusable framework for parsing JSON in Swift.

Why Freddy? Parsing JSON elegantly and safely can be hard, but Freddy is here to help. Freddy is a reusable framework for parsing JSON in Swift. It ha

Big Nerd Ranch 1.1k Jan 1, 2023
[Deprecated] A shiny JSON parsing library in Swift :sparkles: Loved by many from 2015-2021

?? Deprecation Notice ?? Gloss has been deprecated in favor of Swift's Codable framework. The existing Gloss source is not going away, however updates

Harlan Kellaway 1.6k Nov 24, 2022