How to convert json string to json object in java / Various ways to convert string to json object in java

What is JSON?
JSON stands for JavaScript Object Notation and has become the most popular format for transfer and storage of data since due to its light weight nature.


Data between client and server can only be transferred in the form of a string. A json object can be easily converted to a string and vice-versa. Also, it is pretty easy to traverse across a json object for retrieving values.
A json string or json object stores data in key-value format and it can also represent complex parent-child relationships thus making it a preferred way to store and transmit data.
Why String to json object java?
Since json is now frequently used to store data, there might be a case that in your java application, you have a string which is in json format stored in a database or a file or through a form submit event.
The application needs to find value of some key or iterate over this string or display it in a tree view etc. All these are only possible when you have an object representation of this json string.
Fortunately, there are many libraries which make it possible to convert a json string to object in java. Note that all the libraries parse the json string. Thus, the json string should represent a valid json else an error will be thrown.
This post will discuss different libraries that can be utilized for this purpose.
Method 1: Using org.json library
org.json library is also called JSON-Java library. It has org.json.JSONObject class which is used to convert a json string to a json object and vice-versa, create a json object programatically etc.
This class has a constructor which takes a string as argument and returns an instance of org.json.JSONObject which is an object representation of the supplied json string.
This object can also be used to retrieve value for a key from generated json object. Example,

import org.json.JSONObject;
class StringToJsonObject {
   public static void main(String[] args) {
      // json string
      String jsonStr = "{\"name\": \"i30\", \"brand\": \"Hyundai\"}";
      // convert to json object
      JSONObject json = new JSONObject(jsonStr);
      // print object
      System.out.println(json.toString());
      // get value for a key
      String brand = json.get("brand");
      // print value
      System.out.println(brand);
   }
}

Above code when executed produces the following output

{“name”:”i30″,”brand”:”Hyundai”}
Hyundai


org.json library can be added to a project using below dependencies for Maven and Gradle.

<!- – Maven – ->
<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20180813</version>
</dependency>

<!- – Gradle – ->
compile group: ‘org.json’, name: ‘json’, version: ‘20180813’

Method 2: Using Jackson Library
Jackson is a popular library for converting json string to json object, java object(POJO) and vice-versa. It has a class com.fasterxml.jackson.databind.ObjectMapper which has key methods for such conversions.
In order to parse a json string to an object, create an object of this class and use its readTree method with the string as argument.
This method returns an object of com.fasterxml.jackson.databind.JsonNode which is an object representation of json string. It can also be used to retrieve value for a key in generated json object. Example,

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
 
class StringToJsonObject {
   public static void main(String[] args) throws IOException {
      String jsonStr = "{\"name\": \"i30\", \"brand\": \"Hyundai\"}";
      // create object mapper
      ObjectMapper mapper = new ObjectMapper();
      // convert to json object
      JsonNode jsonNode = mapper.readTree(jsonStr);
      System.out.println(jsonNode.toString());
      // get value for a key
      System.out.println(jsonNode.get("name").asText());
   }
}

Above code outputs

{“name”:”i30″,”brand”:”Hyundai”}
i30


Jackson
library can be added to a project using below dependencies for Maven and Gradle.

<!- – Maven – ->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.8</version>
</dependency>

<!- – Gradle – ->
compile group: ‘com.fasterxml.jackson.core’, name: ‘jackson-databind’, version: ‘2.9.8’

Method 3: Using Gson library
Gson is a google library that can also be used for conversion of a json string to object in java and vice-versa. There are two ways in which Gson library can be used to convert json string to an object.
A. Using Gson class
Gson library has a com.google.gson.Gson class which contains a method toJsonTree accepting an object as argument and returns a com.google.gson.JsonElement which is an object representation of the supplied json string.

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
class StringToJsonObject {
   public static void main(String[] args) {
      String jsonStr = "{\"name\": \"i30\", \"brand\": \"Hyundai\"}";
      // create gson object
      Gson gson = new Gson();
      // convert to json tree
      JsonElement jsonTree = gson.toJsonTree(jsonStr);
      System.out.println(jsonTree.toString());
      // get value for a key
      JsonObject jsonObject = jsonTree.getAsJsonObject();
      System.out.println(jsonObject.get("brand").getAsString());
   }
}

Above code outputs

{“name”:”i30″,”brand”:”Hyundai”}
Hyundai

Note that conversion to com.google.gson.JsonObject is required only when you need to retrieve value for an element from json object. In other words, you do not need to call getAsJsonObject method if value retrieval is not required.

B. Using JsonParser class
Gson library has com.google.gson.JsonParser class which can also be used to convert a json string to object. This class has a parse method which returns an object of com.google.gson.JsonElement. This object’s getAsJsonObject returns a json object. Example,

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
class StringToJsonObject {
   public static void main(String[] args) {
      String jsonStr = "{\"name\": \"i30\", \"brand\": \"Hyundai\"}";
      // create parser object
      JsonParser parser = new JsonParser();
      // get json element object
      JsonElement jsonElement = parser.parse(jsonStr);
      // get json object
      JsonObject jsonObject = jsonElement.getAsJsonObject();
      // get value for a key
      System.out.println(jsonObject.get("brand").getAsString());
   }
}

Above code outputs

{“name”:”i30″,”brand”:”Hyundai”}
Hyundai

com.google.gson.JsonObject is a child class of com.google.gson.JsonElement thus the value returned from parse method can directly be casted to com.google.gson.JsonObject thus eliminating the need for invoking getAsJsonObject method.
Modified code can be written as below.

 JsonParser parser = new JsonParser();
 // get json object
 JsonObject jsonObject = (JsonObject)parser.parse(jsonStr);
 // get value for a key
 System.out.println(jsonObject.get("brand").getAsString());

Maven and Gradle dependencies for Gson library are given below.

<!- – Maven – ->
<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.5</version>
</dependency>

<!- – Gradle – ->
compile group: ‘com.google.code.gson’, name: ‘gson’, version: ‘2.8.5’


Hope this post helped you out. Keep visiting!!!

Mark Your Impression

Close Menu