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 :)

Setting the timezone for your Spring Boot app

Purpose of this blog post

Today all non-trivial web applications and web services get deployed in the cloud. One cannot be very sure in which time zone the app is deployed. But sometimes, the app needs to record everything like log statements, database CRUD operations, etc using a specific time zone. Usually using the UTC time zone works best for such applications.

Setting the time zone 

This short blog post is a way to show how this can be achieved in a java application, specifically a Spring or Spring Boot application.

There are many ways to do it like passing arguments to the JVM at start time which sets the time zone.

Example


java -Duser.timezone=PST ... <app-main-class>

But this is not the best solution as your app might not be the only application running on the JVM. There might be other apps running there too.


Setting time zone easily in Spring Boot

Add the following snippet to your Spring Boot application, typically in the main application class to set the desired time zone. The snippet shows the UTC time zone.

Example


import java.util.TimeZone;
import javax.annotation.PostConstruct;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(Ver3Application.class, args);
    }
    
    @PostConstruct
    void setUTCTimeZone(){
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }
}

Happy coding :)