Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/eygraber/jsonapi-kotlin

A Kotlin Multiplatform kotlinx.serialization library for working with JSON:API
https://github.com/eygraber/jsonapi-kotlin

json-api kotlin kotlin-multiplatform kotlinx-serialization

Last synced: about 2 months ago
JSON representation

A Kotlin Multiplatform kotlinx.serialization library for working with JSON:API

Awesome Lists containing this project

README

        

# JSON:API Kotlin

`jsonapi-kotlin` is a Kotlin Multiplatform library for working with [JSON:API](https://jsonapi.org/) documents.

It integrates with [kotlinx-serialization](https://github.com/Kotlin/kotlinx.serialization) to allow deserializing `String` and `JsonObject` representations of a JSON:API document into a Kotlin type, and for serializing the Kotlin type to a `String` or `JsonObject`.

You can use this library with all targets supported by [kotlinx-serialization](https://github.com/Kotlin/kotlinx.serialization).

## Gradle

```kotlin
repositories {
mavenCentral()
}

dependencies {
implementation("com.eygraber:jsonapi-kotlin:0.2.2")

// kotlinx.serialization json is used for the actual serialization
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:")
}
```

## Usage

With a `kotlinx.serialization.json.Json` instance, you can decode a `JsonApiDocument` from a `String` or `JsonObject`:

```kotlin
val json = Json()

val document = json.decodeFromString(string)

// OR

val document = json.decodeFromJsonElement(jsonObject)
```

This will return a generic `JsonApiDocument`. If you know the specific type of `JsonApiDocument` you are working with, you can specify it explicitly so that you don't need to cast:

```kotlin
val resource = json.decodeFromString(string)
val resources = json.decodeFromString(string)
val resourceIdentifier = json.decodeFromString(string)
val resourceIdentifiers = json.decodeFromString(string)
val meta = json.decodeFromString(string)
val errors = json.decodeFromString(string)
```

You can also encode the `JsonApiDocument` to a `String` or `JsonObject`:

```kotlin
json.encodeToString(document)

// OR

json.encodeToJsonElement(document)
```

## Builders

There are convenient builder functions available to assist in creating a `JsonApiDocument` from scratch:

```kotlin
JsonApiDocument
.builder()
.identifier(
type = "articles",
id = JsonApiId("1"),
) {
meta {
put("created", "2019-01-01T00:00:00Z")
}
}
.build()
```

See more examples at [JsonApiBuilderTest](./jsonapi/src/commonTest/kotlin/com/eygraber/jsonapi/JsonApiBuilderTest.kt).

## In Progress

There is a KSP artifact being worked on that will make it easier to extract your domain types from a `JsonApiDocument`.