SalomonBrys / Kotson

Kotlin bindings for JSON manipulation via Gson
MIT License
709 stars 37 forks source link

Add nullable readers #26

Open reitzig opened 7 years ago

reitzig commented 7 years ago

When writing a reader, one has to step through the JSON stream entry by entry. Value accessors like nextInt() fail if they encounter NULL; dealing with JSON elements that can, in Kotlin terms, be Int? is cumbersome.

The workaround is quite easy:

fun JsonReader.nextIntOrNull(): Int? {
    if ( this.peek() != JsonToken.NULL ) {
        return this.nextInt()
    } else {
        this.nextNull()
        return null
    }
}

One could argue for this.peek() == JsonToken.NUMBER (where does the distinction between integers and floats happen, by the way?); that's a design decision between silent and loud parsing errors.

Please include nullable variants into JsonReader.

reitzig commented 7 years ago

The same issue arises for nullable objects or arrays. Any ideas how we could implement it neatly for those two?