Giter Site home page Giter Site logo

japx's Introduction

Japx - JSON:API Decoder/Encoder

CircleCI Version License Platform

Japx

Lightweight JSON:API parser that flattens complex JSON:API structure and turns it into simple JSON and vice versa. It works by transferring Dictionary to Dictionary, so you can use Codable, Unbox, Wrap, ObjectMapper or any other object mapping tool that you prefer.

Basic example

For given example of JSON object:

{
    "data": {
        "id": "1",
        "type": "users",
        "attributes": {
            "email": "[email protected]",
            "username": "john"
        }
    }
}

to parse it to simple JSON use:

let jsonApiObject: [String: Any] = ...
let simpleObject: [String: Any]

do {
    simpleObject = try Japx.Decoder.jsonObject(withJSONAPIObject: jsonApiObject)
} catch {
    print(error)
}

and parser will convert it to object where all properties inside attributes object will be flattened to the root of data object:

{
    "data": {
        "email": "[email protected]",
        "id": "1",
        "username": "john",
        "type": "users"
    }
}

Advanced examples

Parsing relationships

Simple Article object which has its Author:

{
    "data": [
        {
            "type": "articles",
            "id": "1",
            "attributes": {
                "title": "JSON API paints my bikeshed!",
                "body": "The shortest article. Ever.",
                "created": "2015-05-22T14:56:29.000Z",
                "updated": "2015-05-22T14:56:28.000Z"
            },
            "relationships": {
                "author": {
                    "data": {
                        "id": "42",
                        "type": "people"
                    }
                }
            }
        }
    ],
    "included": [
        {
            "type": "people",
            "id": "42",
            "attributes": {
                "name": "John",
                "age": 80,
                "gender": "male"
            }
        }
    ]
}

will be flattened to:

{
    "data": [
        {
            "updated": "2015-05-22T14:56:28.000Z",
            "author": {
                "age": 80,
                "id": "42",
                "gender": "male",
                "type": "people",
                "name": "John"
            },
            "id": "1",
            "title": "JSON API paints my bikeshed!",
            "created": "2015-05-22T14:56:29.000Z",
            "type": "articles",
            "body": "The shortest article. Ever."
        }
    ]
}

Parsing additional information

All nested object which do not have keys defined in JSON:API Specification will be left inside root object intact (same goes for links and meta objects):

{
    "data": [
        {
            "type": "articles",
            "id": "3",
            "attributes": {
                "title": "JSON API paints my bikeshed!",
                "body": "The shortest article. Ever.",
                "created": "2015-05-22T14:56:29.000Z",
                "updated": "2015-05-22T14:56:28.000Z"
            }
        }
    ],
    "meta": {
        "total-pages": 13
    },
    "links": {
        "self": "http://example.com/articles?page[number]=3&page[size]=1",
        "first": "http://example.com/articles?page[number]=1&page[size]=1",
        "prev": "http://example.com/articles?page[number]=2&page[size]=1",
        "next": "http://example.com/articles?page[number]=4&page[size]=1",
        "last": "http://example.com/articles?page[number]=13&page[size]=1"
    },
    "additional": {
        "info": "My custom info"
    }
}

Parsed JSON:

{
    "data": [
        {
            "updated": "2015-05-22T14:56:28.000Z",
            "id": "3",
            "title": "JSON API paints my bikeshed!",
            "created": "2015-05-22T14:56:29.000Z",
            "type": "articles",
            "body": "The shortest article. Ever."
        }
    ],
    "meta": {
        "total-pages": 13
    },
    "links": {
        "prev": "http://example.com/articles?page[number]=2&page[size]=1",
        "first": "http://example.com/articles?page[number]=1&page[size]=1",
        "next": "http://example.com/articles?page[number]=4&page[size]=1",
        "self": "http://example.com/articles?page[number]=3&page[size]=1",
        "last": "http://example.com/articles?page[number]=13&page[size]=1"
    },
    "additional": {
        "info": "My custom info"
    }
}

Parsing with include list

For defining which nested object you want to parse, you can use includeList parameter. For example:

{
    "data": {
        "type": "articles",
        "id": "1",
        "attributes": {
            "title": "JSON API paints my bikeshed!",
            "body": "The shortest article. Ever.",
            "created": "2015-05-22T14:56:29.000Z",
            "updated": "2015-05-22T14:56:28.000Z"
        },
        "relationships": {
            "author": {
                "data": {
                    "id": "42",
                    "type": "people"
                }
            }
        }
    },
    "included": [
        {
            "type": "people",
            "id": "42",
            "attributes": {
                "name": "John",
                "age": 80,
                "gender": "male"
            },
            "relationships": {
                "article": {
                    "data": {
                        "id": "1",
                        "type": "articles"
                    }
                }
            }
        }
    ]
}

Article and Author can be matched using include reference, as defined in JSON:API Specification:

let includeList: String = "author.article.author"
let jsonApiObject: [String: Any] = ...
let recursiveObject: [String: Any] = try Japx.Decoder.jsonObject(with: jsonApiObject, includeList: includeList)

Parsed JSON:

{
    "data": {
        "type": "articles",
        "id": "1",
        "title": "JSON API paints my bikeshed!",
        "body": "The shortest article. Ever.",
        "created": "2015-05-22T14:56:29.000Z",
        "updated": "2015-05-22T14:56:28.000Z",
        "author": {
            "type": "people",
            "id": "42",
            "name": "John",
            "age": 80,
            "gender": "male",
            "article": {
                "type": "articles",
                "id": "1",
                "title": "JSON API paints my bikeshed!",
                "body": "The shortest article. Ever.",
                "created": "2015-05-22T14:56:29.000Z",
                "updated": "2015-05-22T14:56:28.000Z",
                "author": {
                    "type": "people",
                    "id": "42",
                    "name": "John",
                    "age": 80,
                    "gender": "male"
                }
            }
        }
    }
}

Usage

Codable

Japx comes with wrapper for Swift 4 Codable which can be installed as described in installation chapter.

Since JSON:API object can have multiple additional fields like meta, links or pagination info, its real model needs to be wrapped inside data object. For easier parsing, also depending on your API specification, you should create wrapping native object which will contain your generic JSON model:

struct JapxResponse<T: Codable>: Codable {
    let data: T
    // ... additional info like: meta, links, pagination...
}

struct User: JapxCodable {
    let id: String
    let type: String
    let email: String
    let username: String
}

let userResponse: JapxResponse<User> = try JapxDecoder()
                                                    .decode(JapxResponse<User>.self, from: data)
let user: User = userResponse.data

where JapxDecodable and JapxEncodable are defined in JapxCodable file as:

/// Protocol that extends Decodable with required properties for JSON:API objects
protocol JapxDecodable: Decodable {
    var type: String { get }
    var id: String { get }
}

/// Protocol that extends Encodable with required properties for JSON:API objects
protocol JapxEncodable: Encodable {
    var type: String { get }
}

Codable and Alamofire

Japx also comes with wrapper for Alamofire and Codable which can be installed as described in installation chapter.

Use responseCodableJSONAPI method on DataRequest which will pass serialized response in callback. Also, there is keyPath argument to extract only nested data object. So, if you don't need any additional info from API side except plain data, than you can create simple objects, without using wrapping objects/structs.

struct User: JapxCodable {
    let id: String
    let type: String
    let email: String
    let username: String
}

Alamofire
    .request(".../api/v1/users/login", method: .post, parameters: [...])
    .validate()
    .responseCodableJSONAPI(keyPath: "data", completionHandler: { (response: DataResponse<User>) in
        switch response.result {
        case .success(let user):
            print(user)
        case .failure(let error):
            print(error)
        }
    })

Codable, Alamofire and RxSwift

Japx also comes with wrapper for Alamofire, Codable and RxSwift which can be installed as described in installation chapter.

Use responseCodableJSONAPI method from .rx extension on DataRequest which will return Single with serialized response.

let loginModel: LoginModel = ...
let executeLogin: ([String: Any]) throws -> Single<User> = {
    return Alamofire
        .request(".../api/v1/users/login", method: .post, parameters: $0)
        .validate()
        .rx.responseCodableJSONAPI(keyPath: "data")
}

return Single.just(loginModel)
        .map { try JapxEncoder().encode($0) }
        .flatMap(executeLogin)

Installation

Japx is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'Japx'

We've added some more functionalites by conforming to Codable for object mapping or Alamofre for networking. You can find those convinience extansions here:

# Codable
pod 'Japx/Codable'

# Alamofire
pod 'Japx/Alamofire'

# Alamofire and RxSwift
pod 'Japx/RxAlamofire'

# Alamofire and Codable
pod 'Japx/CodableAlamofire'

# Alamofire, Codable and RxSwift
pod 'Japx/RxCodableAlamofire'

Example project

To run the example project, clone the repository, and run pod install from the Example directory first.

Authors

Maintained by Infinum

Infinum

License

Japx is available under the MIT license. See the LICENSE file for more info.

japx's People

Contributors

truba avatar fgulan avatar

Watchers

James Cloos avatar Andrzej Michnia 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.