Learning how to convert Java objects into JSON and vice versa can be very helpful for your work as a full-stack mobile app developer. In this blog post, I will share some code examples that will help you with the most common tasks you’ll encounter when working with JSON and Java. I will cover the following:
- How to create a JSON object in Java
- How to create JSON object from a JSON String
- How to convert Java JSON object into a JSON String
- How to convert Java Object (POJO) into a JSON Object and a JSON String
- Convert JSON Array String in Java Array List
- How to convert Java objects like Map or List into JSON objects
To find other tutorials on how to work with JSON in Java, check the Java JSON tutorials page.
The code examples above should cover most of what you’ll need. However, before you start, you’ll need to download the Google GSON library or add the following dependency to your pom.xml file. As of the time of writing this post, the GSON library is version 2.8.0.
What is Google GSON Library?
Google GSON library is a Java-based library that provides a simple way to convert Java objects into JSON (JavaScript Object Notation) format and vice versa. GSON library is developed by Google and it is an open-source project available on GitHub.
GSON library provides a set of APIs to serialize and deserialize Java objects to and from JSON. It allows you to convert Java objects, such as POJOs (Plain Old Java Objects), arrays, collections, maps, and enums, into JSON format, and vice versa. With GSON, you can easily parse JSON data and convert it to Java objects, or convert Java objects to JSON and transmit them over the network or store them in a database.
GSON Dependency for pom.xml
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency>
Create a JSON object in Java
// Create new JSON Object JsonObject person = new JsonObject(); person.addProperty("firstName", "Sergey"); person.addProperty("lastName", "Kargopolov"); System.out.println(person.toString());
Create Inner/Nested JSON Object
JsonObject person = new JsonObject(); person.addProperty("firstName", "Sergey"); person.addProperty("lastName", "Kargopolov"); // Create Inner JSON Object JsonObject address = new JsonObject(); address.addProperty("country", "ru"); address.addProperty("city", "Moscow"); person.add("address", address); System.out.println(person.toString());
Create JSON Array
// Create JSON Array JsonArray languages = new JsonArray(); languages.add("Russian"); languages.add("English"); languages.add("French"); System.out.println(languages.toString());
Create JSON Array from String
// Create JSON Array from String String jsonString = "{\"firstName\":\"Sergey\",\"lastName\":\"Kargopolov\"}"; JsonParser jsonParser = new JsonParser(); JsonObject objectFromString = jsonParser.parse(jsonString).getAsJsonObject(); System.out.println(objectFromString.toString());
Convert JSON String into JSON Array
JsonParser jsonParser = new JsonParser(); // Convert JSON Array String into JSON Array String jsonArrayString = "[\"Russian\",\"English\",\"French\"]"; JsonArray arrayFromString = jsonParser.parse(jsonArrayString).getAsJsonArray(); System.out.println(arrayFromString.toString())
Convert JSON String into Java Array List
// Convert JSON Array String into Java Array List String jsonArrayString = "[\"Russian\",\"English\",\"French\"]"; Gson googleJson = new Gson(); ArrayList javaArrayListFromGSON = googleJson.fromJson(arrayFromString, ArrayList.class); System.out.println(javaArrayListFromGSON);
Convert Java Plain Object into JSON
//Convert Java Plain Object into JSON Person personPojo = new Person(); personPojo.setFirstName("Sergey"); personPojo.setLastName("Kargopolov"); Gson gsonBuilder = new GsonBuilder().create(); String jsonFromPojo = gsonBuilder.toJson(personPojo); System.out.println(jsonFromPojo);
Convert Java Map into JSON
Gson gsonBuilder = new GsonBuilder().create(); // Convert Java Map into JSON Map personMap = new HashMap(); personMap.put("firstName", "Sergey"); personMap.put("lastName", "Kargopolov"); String jsonFromJavaMap = gsonBuilder.toJson(personMap); System.out.println(jsonFromJavaMap);
Convert Java ArrayList into JSON
Gson gsonBuilder = new GsonBuilder().create(); // Convert Java Array into JSON List languagesArrayList = new ArrayList(); languagesArrayList.add("Russian"); languagesArrayList.add("English"); languagesArrayList.add("French"); String jsonFromJavaArrayList = gsonBuilder.toJson(languagesArrayList); System.out.println(jsonFromJavaArrayList);
All the above code examples in one single file
package com.appsdeveloperblog.json.gsonexample; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class App { public static void main(String[] args) { // Create new JSON Object JsonObject person = new JsonObject(); person.addProperty("firstName", "Sergey"); person.addProperty("lastName", "Kargopolov"); System.out.println(person.toString()); // Create Inner JSON Object JsonObject address = new JsonObject(); address.addProperty("country", "ru"); address.addProperty("city", "Moscow"); person.add("address", address); System.out.println(person.toString()); // Create JSON Array JsonArray languages = new JsonArray(); languages.add("Russian"); languages.add("English"); languages.add("French"); System.out.println(languages.toString()); // Create JSON Array from String String jsonString = "{\"firstName\":\"Sergey\",\"lastName\":\"Kargopolov\"}"; JsonParser jsonParser = new JsonParser(); JsonObject objectFromString = jsonParser.parse(jsonString).getAsJsonObject(); System.out.println(objectFromString.toString()); // Convert JSON Array String into JSON Array String jsonArrayString = "[\"Russian\",\"English\",\"French\"]"; JsonArray arrayFromString = jsonParser.parse(jsonArrayString).getAsJsonArray(); System.out.println(arrayFromString.toString()); // Convert JSON Array String into Java Array List Gson googleJson = new Gson(); ArrayList javaArrayListFromGSON = googleJson.fromJson(arrayFromString, ArrayList.class); System.out.println(javaArrayListFromGSON); //Convert Java Plain Object into JSON Person personPojo = new Person(); personPojo.setFirstName("Sergey"); personPojo.setLastName("Kargopolov"); Gson gsonBuilder = new GsonBuilder().create(); String jsonFromPojo = gsonBuilder.toJson(personPojo); System.out.println(jsonFromPojo); // Convert Java Map into JSON Map personMap = new HashMap(); personMap.put("firstName", "Sergey"); personMap.put("lastName", "Kargopolov"); String jsonFromJavaMap = gsonBuilder.toJson(personMap); System.out.println(jsonFromJavaMap); // Convert Java Array into JSON List languagesArrayList = new ArrayList(); languagesArrayList.add("Russian"); languagesArrayList.add("English"); languagesArrayList.add("French"); String jsonFromJavaArrayList = gsonBuilder.toJson(languagesArrayList); System.out.println(jsonFromJavaArrayList); } }
In summary, GSON library is a widely used Java library for converting Java objects to JSON format and vice versa. It is easy to use, highly customizable, and supports various configurations, making it a popular choice for working with JSON data in Java-based applications.
I hope this tutorial was helpful to you!
Happy learning!