Adds JSON Pointer (RFC 6901) support to Google Gson library. Source code is written in Kotlin by literally importing and modifying original fork by John Lombardo.
This library provides a simple lookup implementation, that tries to always provide a valid Kotlin object for quick and easy dereferencing and direct usage of JSON pointers to read values from Gson's JsonParser when you don't want to keep making specific Kotlin data classes for one off use cases or specific error handling. By using the provided safeX extension properties on JsonElement, you can rest assured that you'll always get a good value back instead of an Exception at runtime.
Consider a JSON error response that you're receiving from your API like this:
{
"email": [
"Enter a valid email address."
]
}
Instead of using Gson().fromJson()
we use Gson's JsonParser
class to get a JsonElement
pointing to the root of the JSON tree, like this:
import com.google.gson.JsonParser
import com.traversient.gsonpointer.pointer
//body is inside a `use` closure from OKHTTP response
val element = JsonParser().parse(body!!.charStream())
// element is JsonElement
Once you have a JsonElement you can get a JsonPointer with it as root, using the convenient Kotlin extension function provided by this library.
val pointer = element.pointer
//pointer is JsonPointer
Once you have a JsonPointer, you can directly access a JsonPointer anywhere in the whole JSON tree using pointer syntax:
val message = pointer.at("/email/0").safeString
//message is the first error String, "Enter a valid email address"
The at()
function always returns a valid JsonElement, even when there is no match. You can use the standard isJsonPrimitive
or other similar methods to determine what you got back. You can more easily use the provided convenience get properties to get either the actual value at the node or a default value that you can check and flow against.
JsonElement.safeNumber
returns anyNumber
found at the pointer, or a0
JsonElement.safeString
returns anyString
found at the pointer, or a""
JsonElement.safeBoolean
returns anyBoolean
found at the pointer, or afalse
JsonElement.safeJsonObject
returns anyJsonObject
found at the pointer, or aJsonObject()
, which works out to an empty JSON object:{}
JsonElement.safeJsonArray
returns anyJsonArray
found at the pointer, or aJsonArray()
, which works out to an empty JSON Array,[]
GsonPointer uses JitPack.io to distribute the library. Add the Jitpack repository to your root project level build.gradle with:
allprojects {
repositories {
jcenter()
maven {
url "https://jitpack.io"
}
google()
}
}
and to your app gradle:
dependencies {
implementation 'com.github.dhiraj:gsonpointer:0.2'
}