Parse JSON String Using Date Format in Java


Parsing JSON in java is quite straight using lib like Gson and Jackson. Gson is light weight lib and very handy to use. We can parse json string containing dates by specifying format using Gson.

Example for parsing json string with date format

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonParserWithDateFormatExample {
    class Info{
        private String name;
        private Date dob;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Date getDob() {
            return dob;
        }
        public void setDob(Date dob) {
            this.dob = dob;
        }
    }
    public static void main(String[] args) throws Exception {
        String date ="1980-01-15 16:45";
        String json = "{"name":"ssp","dob":"1980-01-15 16:45"}";
        Info obj = parseJson(json, Info.class);
        System.out.println(obj.dob);
    }

    public static <T> T parseJson(String json, Class<T> type) throws Exception {
        T result = null;
        try {
            // Gson gson = new Gson();
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm")
                    .create();
            result = gson.fromJson(json, type);
        } catch (Exception e) {
            throw new Exception("Invalid data");
        }
        return result;
    }
}

Here are maven and gradle entries for Gson lib

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.3.1</version>
</dependency>
\'com.google.code.gson:gson:2.3.1\'