Convert String JSON to Object and Object to String JSON in Java \ Spring Boot

Follow the steps below to convert a data from String JSON to Object and Object to String JSON in Java:

  1. The first thing you'll need to do is, add the GSON library dependency to your application.
  2. Create a JsonUtil.java Java class with the following two static methods:
    • toObject(String data, Type type) - Method to convert data from String JSON to Object.
    • toString(Object obj) - Method to convert data from Object to String JSON.

    The following code shows how to do so:

    
    import com.google.gson.Gson;
    import java.lang.reflect.Type;
    
    public class JsonUtil {
    
        public static <T> T toObject(String data, Type type) {
            Gson gson = new Gson();
            return gson.fromJson(data, type);
        }
    
        public static String toString(Object obj) {
            Gson gson = new Gson();
            return gson.toJson(obj);
        }
    
    }
    
  3. Example of using the above static methods:
  4. 
    
    import java.util.List;
    
    public class JsonTest {
    
        public static void main(String[] args) {
            // Converting array JSON to List object
            String jsonArray = "[\"123\",\"456\",\"456\",\"232\"]";
            List<Long> array = JsonUtil.toObject(jsonArray, new TypeToken<List<Long>>() {}.getType());
            System.out.println(array);
    
            // Converting String JSON to User Object
            String strJsonObj = "{\"name\":\"Joe\", \"email\":\"joe@tutorialsbuddy.com\"}";
            User user = JsonUtil.toObject(strJsonObj, User.class);
            System.out.println("Name=" + user.getName() + ", Email= " + user.getEmail());
    
            // Converting user object to String JSON
            String strJson = JsonUtil.toString(user);
            System.out.println(strJson);
        }
    }
    
    Output:
    [123, 456, 456, 232]
    Name=Joe, Email= joe@tutorialsbuddy.com
    {"name":"Joe","email":"joe@tutorialsbuddy.com"}