- How to Convert String to JSON and Vice Versa
- Example of a JSON
- Example JSON Library
- Example JSON Library : JSON to String
- Example GSON Library
- Example GSON Library : JSON to String
- Example Jackson Library
- Example Jackson Library : JSON to String
- Conclusion:
- # JSON in Java
- # Using Jackson Object Mapper
- # Details
- # ObjectMapper instance
- # Deserialization:
- # Method for serialization:
- # JSON To Object (Gson Library)
- # JSONObject.NULL
- # JSON Builder — chaining methods
- # Object To JSON (Gson Library)
- # JSON Iteration
- # optXXX vs getXXX methods
- # Encoding data as JSON
- # Decoding JSON data
- # Extract single element from JSON
- # JsonArray to Java List (Gson Library)
- # Deserialize JSON collection to collection of Objects using Jackson
- # Deserializing JSON array
- # TypeFactory approach
- # TypeReference approach
- # Deserializing JSON map
- # TypeFactory approach
- # TypeReference approach
- # Details
- # Note
- # Remarks
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.
There are three methods to convert JSON to String and Vice Versa in Java
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
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 =""; try < JSONObject jsonObject = new JSONObject(myJSON); System.out.println("JSON Object: "+jsonObject); >catch (JSONException e) < System.out.println("Error "+e.toString()); >> >
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); >>
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 =""; //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); > >
Example GSON Library : JSON to String
To create JSON object inside the com.google.gson we use the JsonObject class and method addPropety() . 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); >>
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 =""; 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()); >> >
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); >> >
Conclusion:
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.
# JSON in Java
JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. JSON is often used in Ajax applications, configurations, databases, and RESTful web services. The Java API for JSON Processing
(opens new window) provides portable APIs to parse, generate, transform, and query JSON.
# Using Jackson Object Mapper
public class Model private String firstName; private String lastName; private int age; /* Getters and setters not shown for brevity */ >
Model outputObject = objectMapper.readValue( "", Model.class); System.out.println(outputObject.getFirstName()); //result: John
String jsonString = objectMapper.writeValueAsString(inputObject)); //result:
# Details
import com.fasterxml.jackson.databind.ObjectMapper;
# ObjectMapper instance
//creating one ObjectMapper objectMapper = new ObjectMapper();
# Deserialization:
T> T readValue(String content, ClassT> valueType)
- valueType needs to be specified — the return will be of this type
- Throws
- IOException — in case of a low-level I/O problem
- JsonParseException — if underlying input contains invalid content
- JsonMappingException — if the input JSON structure does not match object structure
Usage example (jsonString is the input string):
Model fromJson = objectMapper.readValue(jsonString, Model.class);
# Method for serialization:
String writeValueAsString(Object value)
- — `JsonProcessingException` in case of an error — Note: prior to version 2.1, throws clause included IOException; 2.1 removed it.
# JSON To Object (Gson Library)
private class Person public String name; public Person(String name) this.name = name; > >
Gson gson = new Gson(); String json = ""; Person person = gson.fromJson(json, Person.class); System.out.println(person.name); //John
# JSONObject.NULL
If you need to add a property with a null value, you should use the predefined static final JSONObject.NULL and not the standard Java null reference. JSONObject.NULL is a sentinel value used to explicitly define a property with an empty value.
JSONObject obj = new JSONObject(); obj.put("some", JSONObject.NULL); //Creates: System.out.println(obj.get("some"));//prints: null
JSONObject.NULL.equals(null); //returns true
# JSON Builder — chaining methods
(opens new window) while working with JSONObject and JSONArray . JSONObject example
JSONObject obj = new JSONObject();//Initialize an empty JSON object //Before: <> obj.put("name","Nikita").put("age","30").put("isMarried","true"); //After:
JSONArray arr = new JSONArray();//Initialize an empty array //Before: [] arr.put("Stack").put("Over").put("Flow"); //After: ["Stack","Over","Flow"]
# Object To JSON (Gson Library)
private class Person public String name; public Person(String name) this.name = name; > >
Gson g = new Gson(); Person person = new Person("John"); System.out.println(g.toJson(person)); //
(opens new window) jar must be on the classpath.
# JSON Iteration
JSONObject obj = new JSONObject(""); IteratorString> keys = obj.keys();//all keys: isMarried, name & age while (keys.hasNext()) //as long as there is another key String key = keys.next(); //get next key Object value = obj.get(key); //get next value by key System.out.println(key + " : " + value);//print key : value >
JSONArray arr = new JSONArray(); //Initialize an empty array //push (append) some values in: arr.put("Stack"); arr.put("Over"); arr.put("Flow"); for (int i = 0; i arr.length(); i++) //iterate over all values Object value = arr.get(i); //get value System.out.println(value); //print each value >
# optXXX vs getXXX methods
JSONObject and JSONArray have a few methods that are very useful while dealing with a possibility that a value your are trying to get does not exist or is of another type.
JSONObject obj = new JSONObject(); obj.putString("foo", "bar"); // For existing properties of the correct type, there is no difference obj.getString("foo"); // returns "bar" obj.optString("foo"); // returns "bar" obj.optString("foo", "tux"); // returns "bar" // However, if a value cannot be coerced to the required type, the behavior differs obj.getInt("foo"); // throws JSONException obj.optInt("foo"); // returns 0 obj.optInt("foo", 123); // returns 123 // Same if a property does not exist obj.getString("undefined"); // throws JSONException obj.optString("undefined"); // returns "" obj.optString("undefined", "tux"); // returns "tux"
# Encoding data as JSON
// Create a new javax.json.JSONObject instance. JSONObject first = new JSONObject(); first.put("foo", "bar"); first.put("temperature", 21.5); first.put("year", 2016); // Add a second object. JSONObject second = new JSONObject(); second.put("Hello", "world"); first.put("message", second); // Create a new JSONArray with some values JSONArray someMonths = new JSONArray(new String[] "January", "February" >); someMonths.put("March"); // Add another month as the fifth element, leaving the 4th element unset. someMonths.put(4, "May"); // Add the array to our object object.put("months", someMonths); // Encode String json = object.toString(); // An exercise for the reader: Add pretty-printing! /* < "foo":"bar", "temperature":21.5, "year":2016, "message":, "months":["January","February","March",null,"May"] > */
# Decoding JSON data
String json = ",\"months\":[\"January\",\"February\",\"March\",null,\"May\"]>"; // Decode the JSON-encoded string JSONObject object = new JSONObject(json); // Retrieve some values String foo = object.getString("foo"); double temperature = object.getDouble("temperature"); int year = object.getInt("year"); // Retrieve another object JSONObject secondary = object.getJSONObject("message"); String world = secondary.getString("Hello"); // Retrieve an array JSONArray someMonths = object.getJSONArray("months"); // Get some values from the array int nMonths = someMonths.length(); String february = someMonths.getString(1);
# Extract single element from JSON
String json = ""; JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); System.out.println(jsonObject.get("name").getAsString()); //John System.out.println(jsonObject.get("age").getAsInt()); //21
# JsonArray to Java List (Gson Library)
"list": [ "Test_String_1", "Test_String_2" ] >
public ArrayListString> getListString(String jsonList) Type listType = new TypeTokenListString>>() >.getType(); //make sure the name 'list' matches the name of 'JsonArray' in your 'Json'. ArrayListString> list = new Gson().fromJson(jsonList, listType); return list; >
!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> dependency> groupId>com.google.code.gson/groupId> artifactId>gson/artifactId> version>2.7/version> /dependency>
# Deserialize JSON collection to collection of Objects using Jackson
public class Person public String name; public Person(String name) this.name = name; > >
And you want to parse it into a JSON array or a map of Person objects. Due to type erasure you cannot construct classes of List
# Deserializing JSON array
# TypeFactory approach
CollectionType listType = factory.constructCollectionType(List.class, Person.class); ListPreson> list = mapper.readValue(jsonString, listType);
# TypeReference approach
TypeReferencePerson> listType = new TypeReferenceListPerson>>() >; ListPerson> list = mapper.readValue(jsonString, listType);
# Deserializing JSON map
# TypeFactory approach
CollectionType mapType = factory.constructMapLikeType(Map.class, String.class, Person.class); ListPerson> list = mapper.readValue(jsonString, mapType);
# TypeReference approach
TypeReferencePerson> mapType = new TypeReferenceMapString, Person>>() >; MapString, Person> list = mapper.readValue(jsonString, mapType);
# Details
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.CollectionType;
ObjectMapper mapper = new ObjectMapper(); TypeFactory factory = mapper.getTypeFactory();
# Note
- TypeReference should be instantiated using anonymous class
- You should provide generic explicity
Failing to do so may lead to loss of generic type argument which will lead to deserialization failure.
# Remarks
This example focuses on parsing and creating JSON in Java using various libraries such as the Google Gson
(opens new window) library, Jackson Object Mapper, and others..
Examples using other libraries could be found here: How to parse JSON in Java