DEV Community

Will BL
Will BL

Posted on

3 1

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

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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay