1. Introduction
JSON (JavaScript Object Notation) provides a convenient way to store and exchange data between applications. Therefore, as developers, it’s common to work on tasks that require us to extract individual JSON values from a JSON string.
In this tutorial, we’ll explore various ways of extracting these individual values from a JSON string in Kotlin.
2. Using the Kotlinx Serialization Library
First, we can leverage one of Kotlin’s extension libraries, Kotlinx.serialization. This library provides an easy way to serialize and deserialize Kotlin objects to and from JSON.
2.1. Maven and Gradle Dependencies
To use this library with Maven, we need to include its dependency in the pom.xml file:
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-serialization-json-jvm</artifactId>
<version>1.6.2</version>
</dependency>
For Gradle, we add the dependency to the build.gradle file:
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:1.6.2")
2.2. Implementation
With the Kotlinx.serialization dependency included, we can now deserialize a JSON string to obtain certain values from it.
To use this library, we need to get an instance of the parser with the Json() function. We pass a configuration lambda to this function, so we’ll set the ignoreUnknownKeys property to true, which allows us to ignore any unknown properties encountered in the JSON. While not necessary with JsonObjects, as in our case, concrete classes will require setting this property if the JSON object has more properties than properties in our class:
@Test
fun `extract values from JSON string using Kotlinx serialization`() {
val json = Json { ignoreUnknownKeys = true }
val jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"
val jsonObject = json.parseToJsonElement(jsonString).jsonObject
val name = jsonObject["name"]?.jsonPrimitive?.content
val city = jsonObject["city"]?.jsonPrimitive?.content
val age = jsonObject["age"]?.jsonPrimitive?.int
assertEquals("John", name)
assertEquals("New York", city)
assertEquals(30, age)
assertEquals("{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}", jsonObject.toString())
}
In the code above, we use the parseToJsonElement() method to parse the JSON string to a JsonElement. We then get the JsonObject from the JsonElement and use the [] (get) operator to get the value of any property as a JsonPrimitive. Finally, we use the content property of the JsonPrimitive to get the property’s value as a String.
3. Using the Gson Library
Gson is a popular Java library for working with JSON. It provides a simple way to serialize and deserialize Java objects to and from JSON.
3.1. Maven and Gradle Dependencies
To incorporate this dependency into our project when using Maven, we should include it in our pom.xml:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
Similarly, for a Gradle project, let’s add the dependency to the build.gradle file:
implementation("com.google.code.gson:gson:2.10.1")
3.2. Implementation
Accordingly, let’s dive into how to use this Gson library to deserialize a JSON string and obtain individual property values:
@Test
fun `extract values from JSON string using Gson`() {
val gson = Gson()
val jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"
val jsonObject = gson.fromJson(jsonString, JsonObject::class.java)
val name = jsonObject.get("name").asString
val city = jsonObject.get("city").asString
val age = jsonObject.get("age").asInt
assertEquals("John", name)
assertEquals("New York", city)
assertEquals(30, age)
assertEquals("{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}", jsonObject.toString())
}
In the example above, we first create a Gson object and then use its fromJson() method to deserialize the JSON string to a JsonObject. Subsequently, we use the get() method of the JsonObject to get the value of a particular property. Finally, we turn the value into an explicit type, in this case with either the asString or asInt property.
4. Using the Jackson Library
The Jackson library is another high-performance JSON processor for Java, which of course can also be used in Kotlin. It also provides a way to parse JSON into Java objects and vice versa.
4.1. Maven and Gradle Dependencies
To utilize this dependency with Maven, let’s add the specified dependency to the pom.xml file within our project:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-module-kotlin</artifactId>
<version>2.16.0</version>
</dependency>
Likewise, for a Gradle project, let’s add the dependency to the build.gradle file:
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.16.0")
4.2. Implementation
Having included the Jackson library, let’s now see how we can deserialize a JSON property to a string:
@Test
fun `extract values from JSON string using Jackson library`() {
val objectMapper = jacksonObjectMapper()
val jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"
val jsonObject = objectMapper.readValue<JsonNode>(jsonString)
val name = jsonObject.get("name").asText()
val city = jsonObject.get("city").asText()
val age = jsonObject.get("age").asInt()
assertEquals("John", name)
assertEquals("New York", city)
assertEquals(30, age)
assertEquals("{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}", jsonObject.toString())
}
In the above code, we use the jacksonObjectMapper() function to create an ObjectMapper instance. Subsequently, we create a JSON string and convert it to a JsonNode using the readValue() method of the ObjectMapper. Finally, we can get the value of any particular property using the get() method of JsonNode. We’ll transform the property to a String with asText() or an Int with asInt().
5. Conclusion
In this article, we’ve discussed how to get precise values from a JSON String in Kotlin. We explored three ways to achieve this, including kotlinx.serialization, Gson, and Jackson. All of these libraries are widely used in the industry and have their advantages and disadvantages. It’s up to us to choose the library that best suits our needs.
As always, the code samples used in this article can be found over on GitHub.