A type-safe builder for JSON objects in Kotlin, using GSON
A type-safe builder for creating JSON objects and arrays in Kotlin.
Firstly, add the JitPack repository to your project-level build.gradle
file:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Then, in your module’s build.gradle
file, add the dependency:
dependencies {
implementation 'com.ptrbrynt:json-dsl:1.1.2'
}
To create an empty JsonObject
, use this syntax:
val json: JsonObject = jsonObject { }
Add properties like this:
val json: JsonObject = jsonObject {
"my_property" to 7
"another_one" to "hello"
}
You can add a nested object like this:
val json: JsonObject = jsonObject {
"object" to jsonObject {
"hello" to 7
}
}
You can create a JsonArray
like this:
val array: JsonArray = jsonArrayOf(
7,
"hello",
jsonObject {
"a_property" to 'a'
},
jsonArrayOf(
2,
null
)
)
You can add a JsonArray
to a JsonObject
like this:
val obj: JsonObject = jsonObject {
"array" to jsonArrayOf(true, "hello")
}
You can convert from a List
to a JsonArray
like this:
val jsonArray = listOf(2, 4, 6, 623).toJsonArray()
// Alternatively
val jsonArray = jsonArrayOf(listOf(2, 4, 6, 623))
You can also convert a HashMap
to a JsonObject
:
val obj = hashMapOf(Pair("hello", 7), Pair("goodbye", 12)).toJsonObject()