This post will discuss how to parse a JSON String in Kotlin.

Kotlin doesn’t provide any support for converting a JSON string to an object. This post provides an overview of some of the available alternatives to accomplish this.

1. Using Gson

Google’s Gson library can be used to convert a JSON string to an equivalent Java object. You can use the Gson#fromJson() function to facilitate this conversion. The following code demonstrates this:

Download Code

Output:

JSON string is: {"name":"Peter Parker","age":22,"student":{"studentId":"Jon_Snow_22","subjects":["Maths","Science"]}}
Person object: Person(name=Peter Parker, age=22, student=Student(studentId=Jon_Snow_22, subjects=[Maths, Science]))

2. Using Jackson

If you prefer the Jackson library over Gson, you can use its ObjectMapper#readValue() function to convert the JSON string into the specified object. Here’s the sample code:

Download Code

Output:

JSON string is: {"name":"Peter Parker","age":22,"student":{"studentId":"Jon_Snow_22","subjects":["Maths","Science"]}}
Person object: Person(name=Peter Parker, age=22, student=Student(studentId=Jon_Snow_22, subjects=[Maths, Science]))

That’s all about parsing a JSON String in Kotlin.