kson

General

Category
Free
Tag
JSON
License
MIT License
Min SDK
10 (Android 2.3.3–2.3.7 Gingerbread)
Registered
Aug 20, 2017
Favorites
0
Link
https://github.com/fcannizzaro/kson
See also
Flatten
GSON
GetJSON
gson-flatten
fastjson

Additional

Language
Kotlin
Version
1.0.3 (Dec 16, 2017)
Created
Aug 19, 2017
Updated
Dec 16, 2017 (Retired)
Owner
Francesco Saverio Cannizzaro (fcannizzaro)
Contributor
Francesco Saverio Cannizzaro (fcannizzaro)
1
Activity
Badge
Generate
Download
Source code

kson

Kotlin Json DSL

Dependecies

Step 1. Add the JitPack repository to your build file

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
  }
}

Step 2. Add the dependency

dependencies {
  compile 'com.github.fcannizzaro:kson:1.0.3'
}

Usage

val data = json {

  entry("key", "value")

  entry("array") {
    val items = (1..4).map { "item $it" }.reversed()
    items
  }

  entry("array-fast", array("fast 0", "fast 1"))

  entry("another-key", "another-value")

}

println(data.toString(4))

JSON Result

{
  "array-fast": ["fast 0", "fast 1"],
  "array": ["item 4", "item 3", "item 2", "item 1"],
  "another-key": "another-value",
  "key": "value"
}

[ ] Operator

{
  "first": {
    "second" : {
      "key" : "value"
    }
  }
}

You can access "key" by simply doing:

val obj : JSONObject = /* already built */
val key = obj["first"]["second"]["key"] as String

Methods

json(kson: KsonObject.() -> Unit)

Create a JSONObject.

entry(key: String, value: Any?)

entry(key: String, value: () -> Any?)

Add a new entry.

array(vararg items: Any?)

array(items : () -> Iterable<Any?>)

Create a JSONArray.

Exceptions

IllegalArgumentException

  • Entry key cannot be empty.
  • Entry value can only be Int, Double, Float, String, JSONArray, JSONObject or Map.

Author

Francesco Saverio Cannizzaro (fcannizzaro)