DEV Community

loading...

Let's write a tiny JSON parser in Kotlin! Part 3: Bools & Nulls

Will BL
Game Modder and Software Developer
・1 min read

Lets learn how to read the two simplest elements: Booleans and Nulls. These don't get their own diagrams due to their simplicity, but they can be seen in the grammar diagram for values:

A diagram showing the grammar for a JSON value

Booleans

A boolean is super simple, of course - true or false (no yeses and nos like YAML has!)

So we can use the read(String) method we defined earlier to read either true or false:

fun readBoolean(): Boolean? {
    val oldCursor = cursor
    if (read("true") == "true") {
        return true
    }
    cursor = oldCursor
    if (read("false") == "false") {
        return false
    }
    cursor = oldCursor
    return null
}
Enter fullscreen mode Exit fullscreen mode

It will attempt to read true, if that's not there it'll backtrack and try to read false, and if that's not there it'll give up and give you null. Simple.

But not as simple as Null!

Null

Null is the simplest data type (is it even a data type (in JSON)?)

fun readNull(): Boolean {
    val oldCursor = cursor
    if (read("null") == "null") {
        return true
    }
    cursor = oldCursor
    return false
}
Enter fullscreen mode Exit fullscreen mode

Now you can probably see how this works - try to read the symbol null: if it's there, return true ("yes, there is a null here"); if it's not there, put the cursor back to where it was before and return false ("nope, no nulls here")

Conclusion

Awesome, we've learned how to read our first two JSON data types! These, of course, were the simplest - next up we'll be doing Strings - definitely trickier!

Discussion (0)