Phash avatar

Kotlin - work with JSON

phash

Published: 07 Sept 2018 › Updated: 07 Sept 2018Kotlin - work with JSON

Kotlin - work with JSON

The world is full of RESt-JSON Endpoints. What a shame not to use them!

To increase the usefulness of JSON I advice you to use the Json to Kotlin Class Plugin for IntelliJ IDEA/ Android Studio. Just add it to your IDE and use it!

how to use

Get a JSON file, and copy the contents.

{
        "title": "Sample",
        "name": "main_sample",
        "width": 500,
        "height": 500
    }

Right click on your project / package and use "Create Data Class from JSON"
enter a name, and post the code from above.
This will create a new kotlin data class!

{
data class Item(
        var title: String,
        var name: String,
        var width: Int,
        var height: Int
)
    }

That's it!
You can now use

var json = URL("www.mywebservice.com/getData").readText()
var item = Gson().fromJson(json, Item::class.java)
println(item.title)
...

smooth, isn't it?

Leave Kotlin - work with JSON to:

Written by

Read more #kotlin posts


Best Posts From Phash

We have not curated any of phash's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Phash