Kotlin - work with JSON

in #kotlin6 years ago

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?