I created this JSON Parser to be a simple, lightweight, and painless way to navigate and extract values from JSON data.
Benefits:
- Flexible: no need to create data classes into which JSON data is deserialized.
- Lightweight: mere kilobytes, no other third-party dependencies.
Add this project as a submodule to your Android application with Import Gradle Module
OR
Just download the Kotlin file Sleek.kt and add it into your project.
First instantiate a Sleek
object from the JSON data. The constructor accepts the source JSON string. Afterwards:
-
If the root JSON value is an object, the index operator
[a]
(wherea
is of typeString
) returns aSleek
object containing the value in the dictionary associated with keya
. If not found, throwsJsonKeyException
-
If the root JSON value is an array, the index operator
[a]
(wherea
is of typeInt
) returns aSleek
object containing the value in the array at indexa
. If not found, throwsJsonArrayIndexOutOfBoundsException
. -
Chain these for a nice JSON parsing experience!
-
When you have a Sleek object that contains a single JSON literal, simply use:
.string
to return aString?
.int
to return aInt?
.float
to return aFloat?
.boolean
to return aBoolean?
- All of the above values are
null
only if the value is a JSONnull
literal. Attempting to cast to a mismatched type throws an exception.
-
When you have a Sleek object that is based on a JSON array, you have the option of using
.list
to return an array of typeList<Sleek>
containing the entries of the JSON array. -
Strictly typed lists are also available. Use
stringList
to returnList<String?>
intList
to returnList<Int?>
floatList
to returnList<Float?>
booleanList
to returnList<Boolean?>
-
When you have a Sleek object that is based on a JSON object, you have the option of using
.map
to return a map of typeMap<String, Sleek>
containing the fields of the object. -
Strictly typed maps are also available. Use
stringMap
to returnMap<String, String?>
intMap
to returnMap<String, Int?>
floatMap
to returnMap<String, Float?>
booleanMap
to returnMap<String, Boolean?>
-
You can also use the following boolean functions:
isJsonObject
isJsonArray
isJsonLiteral
isJsonNumber
isJsonString
isJsonBoolean
isJsonNullValue
val jsonData = Sleek("""[ 1, "thing", { "thang": 24 } ]""")
val jsonData2 = Sleek("""[1, 2, 3.5, 4, null, -7.1e4]""")
jsonData[2]["thang"].int
//24
jsonData[1].string
//thing
jsonData.list
//An array containing a Sleek object of each element of the JSON array: 1, "thing", and {"thang":24}
jsonData[2].map
//A map containing the pair "thang" and a Sleek object based on 24.
jsonData2.floatList
// List<Int?> => [1.0, 2.0, 3.5, 4.0, null, -71000.0]