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:
- The first thing you'll need to do is, add the GSON library dependency to your application.
- 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.
- Example of using the above static methods:
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);
}
}
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\":\"[email protected]\"}";
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);
}
}