Avatar ·

How to parse JSON in Kotlin: best libraries and code examples

Hello, colleagues! I just started learning Kotlin after Java and encountered a typical task — I need to parse a JSON string into an object. In Java I used Gson or Jackson, but in Kotlin I want to do it elegantly and idiomatically.\n\nI have this JSON from an API:\n
{\n  "userId": 1,\n  "id": 1,\n  "title": "delectus aut autem",\n  "completed": false\n}
\n\nI tried using the built-in JSONObject from the Android SDK, but the code turns out terrible:\n
val jsonString = """{"userId":1,"id":1,"title":"delectus aut autem","completed":false}"""\nval jsonObject = JSONObject(jsonString)\nval userId = jsonObject.getInt("userId")\nval id = jsonObject.getInt("id")\nval title = jsonObject.getString("title")\nval completed = jsonObject.getBoolean("completed")
\n\nThis is just