Lazily deserialize JSON into strongly typed Swift objects

Overview

LazyObject

Coverage Status Build Status MIT licensed CocoaPods Swift

Lazily deserialize JSON into strongly typed Swift objects, with a few getter style options.

Is your app using it? Let me know!

Installation

Quickly install using CocoaPods:

pod 'LazyObject'

Or manually install:

  1. Clone this repository
  2. Build the LazyObject project
  3. Add the resulting framework file to your project
  4. ?
  5. Profit

API

Let's look at an example model to show off some of the functionality:

class Bank: LazyObject {
    var money: Double       { return try! objectFor(#function) } // Automagically converts #function to a "money" string
    var getPaid: Bool?      { return try? objectFor("get_paid") } // Will be nil if called and key/value don't exist
    var security: [Person]? { return try? objectFor(#function) } // Works with arrays of other LazyObjects as well
    var debt: Double        { return try! objectFor("accounting.books.cooked") } // Nested key paths are supported 
}

Models are instantiated from JSON dictionaries:

// The dictionary passed here is the JSON response
let bank = Bank(dictionary: ["money": 9999, "get_paid": true])

There is also a convenience extension for instantiating from JSON arrays:

let banks = Bank.fromArray(jsonArrayOfDictionaries)

Date Formattables

Since many services have varying date formats, LazyObject provides an easy way to specify which standard or custom format you'd like to conform to.

class Retirement: LazyObject, ISO8601Formattable {
  var date: NSDate?   { return try? dateFor(#function) }
}

Note: For dates, you must specifically use the dateFor() method so it will choose the correct formatter from the cache.

Any of your base or sub-classes can conform to one of the supported protocols:

  • ISO8601Formattable (e.g. "2016-04-24T14:42:42.424Z")
  • RFC3339Formattable (e.g. "2016-04-24T14:42:42Z")
  • RFC1123Formattable (e.g. "Sun, 24 Apr 2016 14:42:42 +0000")
  • RFC850Formattable (e.g. "Sunday, 24-Apr-16 14:42:42 UTC")
  • EpochFormattable (e.g. "1461508962.424" as a string or 1461508962.424 as a double)

Or you're free to extend LazyDateFormattable to create custom date conversions (look at how the above protocols are implemented for an example).

All formatters above are created once and cached for re-use, and it is recommended you do the same if you create custom formattables since they tend to be expensive to create.

Key Getter Options

The objectFor method supports a couple variations for key names:

  • #function: Converts whatever the property name is into a string (e.g. var help becomes "help"). Note that a property name like myProperty will be converted to "myProperty" not my_property, so feel free to extend LazyObject if you require that.
  • keyPath: Can be a string containing a single key like first_name or a key path to a nested value like location.latitude

Optionals

Notice in the example that you can use try? to ensure optional safety on the properties. If you're feeling confident, you can use try! to force it but you may receive one of a few runtime errors if it doesn't succeed.

Convertibles

Aside from standard JSON data types, the following types are seamlessly supported:

  • NSDate
  • NSURL
  • NSNumber

Custom Convertibles

If you want to seamlessly convert a custom value, such as to create an NSNumber from a string value, you can create your own extensions of LazyConvertible like so:

// Note: this example is actually already part of the library, so no need to extend NSNumber

import Foundation

extension NSNumber: LazyConvertible {

    public static func convert(value: AnyObject?) throws -> NSNumber {
        guard let string = value as? String else {
            throw LazyMappingError.UnexpectedTypeError(value: value, type: String.self)
        }

        let formatter = NSNumberFormatter()
        guard let number = formatter.numberFromString(string) else {
            throw LazyMappingError.CustomError(message: "'\(string)' is not a valid input for NSNumber instantiation")
        }

        return number
    }

}

This will allow you to seamlessly support any type of valid NSNumber, whether from string or from a number value, just by using the normal objectFor methods.

Setting Values

LazyObject is focused mostly on read-only models, but you can still easily expose a setter on the model if necessary:

class Object: LazyObject {
    var id: NSNumber? {
        get {
            return try? objectFor(#function)
        }
        set {
            setObject(newValue, setter: #function)
        }
    }
}

Note: Similar to the getter methods, both the setter #function can be used or the keyPath can be used to reference the key name to update.

Supports

Swift, ARC & iOS 9+

A little help from my friends

Please feel free to fork and create a pull request for bug fixes or improvements, being sure to maintain the general coding style, adding tests, and adding comments as necessary.

Credit

This library is influenced by CottonObject and Mapper

You might also like...
Swish is a networking library that is particularly meant for requesting and decoding JSON via Decodable
Swish is a networking library that is particularly meant for requesting and decoding JSON via Decodable

Swish Nothing but net(working). Swish is a networking library that is particularly meant for requesting and decoding JSON via Decodable. It is protoco

To practice URLSession to fetch json data from open weather API
To practice URLSession to fetch json data from open weather API

โ›…๏ธ weatherApp-iOS-practice ๐Ÿ“Œ ๊ธฐ๋Šฅ ์ƒ์„ธ ๋„์‹œ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜๋ฉด ํ˜„์žฌ ๋‚ ์”จ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์™€ ํ™”๋ฉด์— ํ‘œ์‹œ๋˜๊ฒŒ ๋งŒ๋“ค์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค

Enable WebSocket in OPC DA/AE Server with JSON return, first time ever
Enable WebSocket in OPC DA/AE Server with JSON return, first time ever

WebSocket4OPC Enable WebSocket in OPC DA/AE Server with JSON return, first time ever DCOM was developed more than 2 decades ago, wich was the pillar o

Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and moreโ€ฆ)
Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and moreโ€ฆ)

Perfect: Server-Side Swift ็ฎ€ไฝ“ไธญๆ–‡ Perfect: Server-Side Swift Perfect is a complete and powerful toolbox, framework, and application server for Linux, iO

Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux.

BlueSocket Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux. Prerequisites Swift Swift Open Source swift-5.1

Swift Express is a simple, yet unopinionated web application server written in Swift
Swift Express is a simple, yet unopinionated web application server written in Swift

Documentation h5 align="right"a href="http://demo.swiftexpress.io/"Live ๐Ÿง server running Demo img src="https://cdn0.iconfinder.com/data/icons/

Swift backend / server framework (Pure Swift, Supports Linux)

NetworkObjects NetworkObjects is a #PureSwift backend. This framework compiles for OS X, iOS and Linux and serves as the foundation for building power

Swift-multipart-formdata - MultipartFormData: Build multipart/form-data type-safe in Swift

MultipartFormData Build multipart/form-data type-safe in Swift. A result builder

Quickstart-ios-swift-grpc - Quickstart for integrating Approov with iOS apps in Swift that make API requests you wish to protect using GRPC
Comments
  • Manual Installation

    Manual Installation

    CocoaPods is an awesome tools and make our life really easier, but there are some devs who still don't know how to use them.

    It would be cool to add the Manual installation guide in your README.md. You can take a look at my iOS Readme Template to see how you can do it.

    ++ enhancement 
    opened by lfarah 1
Owner
rob phillips
If I only scrape a living, at least it's a living worth scraping. If there's no future in it, at least it's a present worth remembering.
rob phillips
An Alamofire extension which converts JSON response data into swift objects using EVReflection

AlamofireJsonToObjects ?? This is now a subspec of EVReflection and the code is maintained there. ?? You can install it as a subspec like this: use_fr

Edwin Vermeer 161 Sep 29, 2022
Meet Corvus, the first strongly declarative server-side framework.

Corvus Corvus is the first truly declarative server-side framework for Swift. It provides a declarative, composable syntax which makes it easy to get

null 42 Jun 29, 2022
Elegantly connect to a JSON api. (Alamofire + Promises + JSON Parsing)

โš  Important Notice: Farewell ws... hello Networking ! Networking is the next generation of the ws project. Think of it as ws 2.0 built for iOS13. It u

Fresh 351 Oct 2, 2022
Access Xcode Server API with native Swift objects.

Xcode Server SDK Use Xcode Server's API with native Swift objects. First brought to you in Buildasaur, now in an independent project. This is an unoff

Buildasaurs 401 Dec 29, 2022
DBNetworkStack is a network abstraction for fetching request and mapping them to model objects

DBNetworkStack Main Features ?? Typed network resources ?? Value oriented architecture ?? Exchangeable implementations ?? Extendable API ?? Composable

DB Systel GmbH 33 Jan 10, 2022
An iOS library to route API paths to objects on client side with request, mapping, routing and auth layers

WANetworkRouting Developed and Maintained by ipodishima Founder & CTO at Wasappli Inc. Sponsored by Wisembly A routing library to fetch objects from a

null 10 Nov 20, 2022
Swift/Obj-C HTTP framework with a focus on REST and JSON

Now Archived and Forked PMHTTP will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork of PHMT

Postmates Inc. 509 Sep 4, 2022
A barebones Swift HTTP client with automatic JSON response parsing.

HTTP Client A barebones Swift HTTP client with automatic JSON response parsing. Installation Add HTTP Client as a dependency through Xcode or directly

Joe Masilotti 30 Oct 11, 2022
Lightweight REST and JSON library for Swift.

RestEssentials is an extremely lightweight REST and JSON library for Swift and can be used on iOS, iPadOS, macOS, tvOS, and watchOS. Features Easily p

null 37 Nov 2, 2022
TupleResult - A micro library that easily converts tuple result into Swift.Result

TupleResult A micro library that easily converts c-style tuple result into Swift

Ernest SeongHo Hong 0 Jan 29, 2022