Kotlin’s a great language for JSON

Jesse Wilson
May 15, 2017 · 2 min read

Heads up, we’ve moved! If you’d like to continue keeping up with the latest technical content from Square please visit us at our new home https://developer.squareup.com/blog

Though it has its wrinkles, I really like JSON. It’s easy to read, pretty fast to parse, and refreshingly simple. Here’s a sample message from GitHub’s exemplar API:

Kotlin’s concise immutable data classes make it easy to build a basic model for this JSON.

That’s it. No equals(), hashCode(), or toString() boilerplate. We don’t even need a builder! Let’s extend the model to take advantage of Kotlin’s default values and explicit nulls:

Default values fill in the gaps when decoding JSON from the network. I like that I can leave them out when creating sample data in my test cases. Explicit nullable types prevent data problems.

Today we’re releasing Moshi 1.5 with powerful Kotlin support via the moshi-kotlin module. Moshi’s type adapters and annotations bind JSON to an idiomatic data model.

This class uses proper types instead of strings for the issue’s state and timestamps. The @Json annotation maps snake_case names in JSON to camelCase property names in Kotlin.

To set this up I need a Moshi.Builder and a JsonAdapter. I can use Kotlin’s raw strings to embed a sample message right in the code.

If you’re using JSON, Moshi and Kotlin help you to build better models with less code. Note that moshi-kotlin uses kotlin-reflect for property binding. That dependency is large by Android standards (1.7 MiB / 11,500 methods). We’re thinking of creative ways to address that!

This post is part of Square’s “Square Open Source ♥s Kotlin” series.

Square Corner Blog

Buying and selling sound like simple things - and they…

Jesse Wilson

Written by

Android and jokes.

Square Corner Blog

Buying and selling sound like simple things - and they should be. Somewhere along the way, they got complicated. At Square, we're working hard to make commerce easy for everyone.

Jesse Wilson

Written by

Android and jokes.

Square Corner Blog

Buying and selling sound like simple things - and they should be. Somewhere along the way, they got complicated. At Square, we're working hard to make commerce easy for everyone.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store