Java – Serialize/deserialize simple objects using GSON – No time zone indicator error

Serialize/deserialize simple objects using GSON – No time zone indicator error… here is a solution to the problem.

Serialize/deserialize simple objects using GSON – No time zone indicator error

I have an API that receives requests and generates JSON for return. The JSON is generated using the following object and my utility class.

When the JSON

is returned to the application, I actually use the exact same utility class to serialize the JSON back to the object.

However, I get an exception (see below). How do I fix this? I’ve tried almost everything I can find online, but I’m not having any luck.

Object:

public class MyPerson() {
    private String name;
    private Date lastEdited;
}

Utility class for conversion:

public class GsonUtils {

private static final Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'hh:mm:ss")
            .create();

public static String deserializeObjectToJSON(Object obj) {
        return gson.toJson(obj);
    }

public static <T> Object serializeObjectFromJSON(String json, Class<T> classType) {
        return gson.fromJson(json, classType);
    }

public static <T> List<T> serializeListOfObjectsFromJSON(String json, Type listType) {
        return gson.fromJson(json, listType);
    }
}

Error:

Caused by: java.text.ParseException: Failed to parse date ["2019-02-12T12:00:00.0"]: No time zone indicator     at com.google.gson.internal.bind.util.ISO8601Utils.parse( ISO8601Utils.java:274) ~[gson-2.8.5.jar:na]    at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:85) ~[gson-2.8.5.jar:na]    ... 66 common frames omitted

Edit:

Accepted the suggestion and updated the utility class, same error :

Caused by: java.text.ParseException: Failed to parse date ["2019-02-12T12:00:00.0"]: No time zone indicator
    at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:274) ~[gson-2.8.5.jar:na]
    at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:85) ~[gson-2.8.5.jar:na]
    ... 66 common frames omitted

Solution

yyyy-MM-dd'T'hh:mm:ss. S
Use this as your date format

Related Problems and Solutions