Search code examples
javagotimedate-formattingjackson-databind

Jackson can't deserialize date set from Golang Api


I'm working on a Golang Micro-service which uses Java based Cucumber tests for BDDs.

There is a date variable inside the schema and it is defined as:

startDate *time.Time

I set this value as:

t := time.Now()
startDate = &t

When I run the BDDs through Java program, I get this error:

Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.util.Date from String "2021-06-11T10:53:57.1124553+05:30": not a valid representation (error: Failed to parse Date value '2021-06-11T10:53:57.1124553+05:30': Unparseable date: "2021-06-11T10:53:57.1124553+05:30")

While in my BDD tests, I have:

private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(dateFormat);

I'm relatively new to Golang and facing issues while dealing with dates.

Until Now, I have tried:

t := time.Now().Format(time.RFC3339)
tt, _ := time.Parse(time.RFC3339, t)
startDate = &tt

I even tried with the time.LoadLocation(), but I am unable to figure out the issue.


Solution

  • The Go code you provided will not impact the way how the Time instance will be serialized as you are parsing it back into Time after serializing it to a string.

    If you have control over how your date fields are serialized, you can apply the following format that should be aligned with what you provided to Jackson's ObjectMapper:

    now := time.Now()
    formattedDate := now.Format("2006-01-02T15:04:05.000Z0700")
    

    If you don't have control over how the date is serialized on the Go side, you could also adjust the date format on the Java side. The following example assumes that time.RFC3339 is used by Go:

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");