Tuesday, January 23, 2018

Small JSON utility methods for your Spring Boot app

JSON is almost the lingua-franca when it comes to communication between web-services or Ajax based browser to server communication, though its not limited to just these two.

There are many good JSON utilities and libraries like the the faster jackson library. The maven repository page is here.

Purpose of this blog post


I am sharing two simple methods which I have used and continue to use a lot in all my projects requiring JSON. I understand that there maybe better versions and utilities out there, but I wanted to share what I learnt and developed and use in my work.

Using Faster Jackson in your Spring Boot app


Include the following dependency in your pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

In your project's utility class, you can add the following methods - to convert to and from JSON.

Method 1 - To convert a JSON string to a Java POJO. 

This is typically useful when the browser sends back form data to the server and you want to process it and convert it to a POJO.


/**
 * Converts a JSON string to a Java POJO
 * 
 * @param json
 *            the JSON string
 * @param clazz
 *            the class of the POJO that will be returned
 * @return instance of T
 */
public static <T> T fromJson(String json, Class<T> clazz) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    try {
        return (T) mapper.readValue(json, clazz);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    return null;
}


Method 2 - To convert a POJO to a JSON string

This is typically useful when the server sends data back to the browser. Notice that you can send back JSON as a simple String or with proper indentations and line feeds so that the string prints out a well formatted JSON.


/**
 * Convert a Java POJO to a JSON string
 * 
 * @param obj
 *            the Java POJO
 * @param prettyPrint
 *            if true then the string will be indented and the 
 *            {@link ObjectMapper#writerWithDefaultPrettyPrinter()}
 *            will be used to generate a well formatted human 
 *            readable JSON string
 * @return String in json format
 */
public static String toJson(Object obj, boolean prettyPrint) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    String s = null;
    try {
        s = prettyPrint ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj)
                : mapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        LOG.error(e.getMessage(), e);
    }
    return s;
}   

Happy coding :)

No comments: