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](whereais of typeString) returns aSleekobject 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](whereais of typeInt) returns aSleekobject 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:
.stringto return aString?.intto return aInt?.floatto return aFloat?.booleanto return aBoolean?- All of the above values are
nullonly if the value is a JSONnullliteral. 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
.listto return an array of typeList<Sleek>containing the entries of the JSON array. -
Strictly typed lists are also available. Use
stringListto returnList<String?>intListto returnList<Int?>floatListto returnList<Float?>booleanListto returnList<Boolean?>
-
When you have a Sleek object that is based on a JSON object, you have the option of using
.mapto return a map of typeMap<String, Sleek>containing the fields of the object. -
Strictly typed maps are also available. Use
stringMapto returnMap<String, String?>intMapto returnMap<String, Int?>floatMapto returnMap<String, Float?>booleanMapto returnMap<String, Boolean?>
-
You can also use the following boolean functions:
isJsonObjectisJsonArrayisJsonLiteralisJsonNumberisJsonStringisJsonBooleanisJsonNullValue
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]