/kotlin-json-dsl

Kotlin DSL library that makes it easy to generate json

Primary LanguageKotlinApache License 2.0Apache-2.0

Kotlin-Json-DSL

GitHub

Simple Kotlin DSL library for creating JSON strings.

Installation

Gradle

dependencies {
    implementation 'io.github.kshired:kotlin-json-dsl:0.0.1'
}

Gradle(kotlin)

dependencies {
    implementation("io.github.kshired:kotlin-json-dsl:0.0.1")
}

Maven

<dependency>
    <groupId>io.github.kshired</groupId>
    <artifactId>kotlin-json-dsl</artifactId>
    <version>0.0.1</version>
</dependency>

Usage

val json = jsonObject {
    "name" to "John"
    "age" to 30
    "isStudent" to true
    "address" to jsonObject {
        "street" to "Main St"
        "city" to "New York"
    }
    "friends" to jsonArray {
        jsonObject {
            "name" to "Alice"
            "age" to 25
        }
        jsonObject {
            "name" to "Bob"
            "age" to 35
        }
    }
}

val jsonString = json.toJsonString()
val prettyJsonString = json.toPrettyJsonString()

Output of the above code:

  • jsonString:
{"name":"John","age":30,"isStudent":true,"address":{"street":"Main St","city":"New York"},"friends":[{"name":"Alice","age":25},{"name":"Bob","age":35}]}
  • prettyJsonString:
{
  "name": "John",
  "age": 30,
  "isStudent": true,
  "address": {
    "street": "Main St",
    "city": "New York"
  },
  "friends": [
    {
      "name": "Alice",
      "age": 25
    },
    {
      "name": "Bob",
      "age": 35
    }
  ]
}