How to Convert String to JSON and Vice Versa
In this tutorial, we will learn about How to Convert String to JSON and Vice Versa. First things first, What is JSON?
JSON is an acronym for JavaScript Object Notation. It is lightweight data transferring format among different web services. Mostly it is used to build an API.
Example of a JSON
This is an example of JSON it stores data in key-value format and values can be the array of another primitive datatype or another JSON.
myJSON = {
"course":"Java",
"price":8000,
"duration":"3 Months"
};
There are three methods to convert JSON to String and Vice Versa in Java
-
Using JSON Library
-
Using Gson Library
-
Using Jackson Library
While running a program where these libraries are included we need to download these jar files and add them inside the project according to IDE otherwise functions from these libraries will not support and cause an error. You can refer following links to download these libraries
Download org.json.jar
Download gson-2.2.2.jar
Download org.codehaus.jackson.jar
Let's look one by one with the help of examples.
Example JSON Library
In the code given below, we have a JSON
data stored in the form of String. Converting a string JSON
is very much convenient to perform multiple actions. JSONObject
is a class of org.json
package that converts a string to an JSON
object.
import org.json.JSONException;
import org.json.JSONObject;
public class StudyTonight
{
public static void main(String[] args)
{
String myJSON ="{\"name\":\"studytonight\",\"address\":\"Noida\"}";
try
{
JSONObject jsonObject = new JSONObject(myJSON);
System.out.println("JSON Object: "+jsonObject);
}
catch (JSONException e)
{
System.out.println("Error "+e.toString());
}
}
}
JSON Object: {"address":"Noida","name":"studytonight"}
Example JSON Library : JSON to String
In the above code, we learned how to convert a string to a JSON object and now we can go for JSON object to a string we will learn creating an object from scratch also. Firstly we will create a JSON object and add values this class has JSONObject.put()
method which accepts two parameter key and value.
import org.json.JSONObject;
public class StudyTonight
{
public static void main(String[] args)
{
//Creating a JSON Object
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "studytonight");
jsonObject.put("address", "Noida");
//Converting JSON Object using toString() method
String myJSONString = jsonObject.toString();
System.out.println("JSON String: "+myJSONString);
}
}
JSON String: {"address":"Noida","name":"studytonight"}
Example GSON Library
Whatever the two things we did in the above code block we will do the same stuff using the Gson library. This library is developed by Google and widely used in the industry. JsonParser
is a class that is responsible to parse a string and parse()
is a method that accepts a string. Finally, we use getAsJsonObject()
to get all the above conversion in JsonObject format.
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class StudyTonight
{
public static void main(String[] args)
{
//JSON String
String myJSON ="{\"name\":\"studytonight\",\"address\":\"Noida\"}";
//JSON Parser from Gson Library
JsonParser parser = new JsonParser();
//Creating JSONObject from String using parser
JsonObject JSONObject = parser.parse(myJSON).getAsJsonObject();
System.out.println("Object: "+JSONObject);
}
}
Object: {"name":"studytonight","address":"Noida"}
Example GSON Library : JSON to String
To create JSON object inside the com.google.gson
we use the JsonObject class and method addProperty()
. addProperty() which will accept two parameters i.e. key and value which will be added to a JSON object.
import com.google.gson.JsonObject;
public class StudyTonight
{
public static void main(String[] args)
{
//Creating Json Object
JsonObject JSONObject = new JsonObject();
JSONObject.addProperty("name", "studytonight");
JSONObject.addProperty("address", "Noida");
//Converting Json Object to String
String myJSON = JSONObject.toString();
System.out.println("String: "+myJSON);
}
}
String: {"name":"studytonight","address":"Noida"}
Example Jackson Library
Jackson is a library that provides a lot of flexibility while working with JSON. We need to create a mapper from ObjectMapper class then we create a JsonFactory class object from a mapper and call that mapper to create a parser and finally this parse will create actually JSON object for us using readTree()
method. readTree()
will accept the parser object and trace the hierarchy of JSON.
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
public class StudyTonight
{
public static void main(String[] args)
{
//JSON String
String myJSON ="{\"name\":\"studytonight\",\"address\":\"Noida\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory();
try
{
JsonParser parser = factory.createJsonParser(myJSON);
JsonNode actualObj = mapper.readTree(parser);
System.out.println("Object: "+actualObj);
}
catch(Exception e)
{
System.out.println("Error: "+e.toString());
}
}
}
Object: {"name":"studytonight","address":"Noida"}
Example Jackson Library : JSON to String
To create String from Json object Jackson library provides writeValueAsString()
method in ObjectMapper
class. This value accepts JSON objects and returns the string.
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
public class StudyTonight
{
public static void main(String[] args)
{
ObjectMapper mapper = new ObjectMapper();
// create a JSON object
ObjectNode JSONObject = mapper.createObjectNode();
JSONObject.put("name", "studytonight");
JSONObject.put("address", "Noida");
try
{
//Json object to String
String JSONString = mapper.writeValueAsString(JSONObject);
System.out.println("String: "+JSONString);
}
catch(Exception e)
{
System.out.println("Error "+e);
}
}
}
String: {"name":"studytonight","address":"Noida"}
Conclusion:
JSON object is a universal standard for web services and if you are working with REST services then you must know how to work with JSON format. Yes, you can always work with JSON as a string, and perform different string operations to get the data from the string, like, string split, compare two strings in Java to extract data, but it is always best to get the JSON string converted into a JSON object and then use proper functions to work with it.
JSON is JavaScript Object Notation and it is very popular for building web services like RESTful APIs. We used json
, gson
, and Jackson
libraries to convert JSON to String and String to JSON.