Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing/Deserializing simple object using GSON - No time zone indicator error

Tags:

java

json

gson

I have an API that takes requests and generates returned JSON. That JSON is generated using the object below 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 into the object.

However, I get an exception (see below). How do I get around that? I've tried just about everything I can find online, I haven't had any luck.

Object:

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

Utility class for converting:

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:

Took the suggestions 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
like image 555
user10776719 Avatar asked May 12 '26 06:05

user10776719


2 Answers

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

like image 126
Kiran S Avatar answered May 13 '26 20:05

Kiran S


Figured out the issue

I changed the format to -

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

This link helped me figure out my issue (UTC time formatting was what I wanted):

Java Date to UTC using gson

like image 21
user10776719 Avatar answered May 13 '26 19:05

user10776719



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!