Skip to content

bornfight/swift-jab

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

70 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JAB - JSON:API Bridge

A lightweight Swift library for transforming JSON:API responses into "usual" REST API responses.

Usage

The principle class to use is JSONAPIDeserializer, which has a reference to a JSONDecoder handling the actual decoding of JSON responses.

For example:

let jsonDecoder: JSONDecoder = {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    decoder.dateDecodingStrategy = .millisecondsSince1970
    return decoder
}()
let jsonApiDeserializer = JSONAPIDeserializer(decoder: jsonDecoder)

The deserializer expects an object conforming to Codable to be deserialized from the response. If there was a Car object looking a little something like this

struct Car: Codable, JSONAPIIdentifiable {
    let identifier: String
    let mark: String
    let model: String
    let color: String
    let maxSpeed: Int
}

Then the JSON:API response the deserializer would expect to find would look a bit like

{
    "jsonapi": {
        "version": "1.0"
    },
    "data": {
        "type": "cars",
        "id": "1",
        "attributes": {
            "mark": "Toyota",
            "model": "Yaris",
            "color": "Red",
            "max_speed": 250
        }
    }
}

It could then be decoded like so:

let rawJsonString = "..."
let jsonData = rawJsonString.data(using: .utf8)!
let car: Car = try! jsonApiDeserializer.deserialize(data: jsonData)

Handling recursive properties

Recursive properties must be handled with special care.

let jsonApiDeserializer = JSONAPIDeserializer(decoder: jsonDecoder)
jsonApiDeserializer.strategy = .handleRecursiveCases

let rawJsonString = "..."
let jsonData = rawJsonString.data(using: .utf8)!
let car: Car = try! jsonApiDeserializer.deserialize(data: jsonData)

About

Swift library for handling JSON:API responses

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •