0

I'm in the process of editing some JSON files. I deserialize them into java objects, edit, and then write them back to JSON format, using Gson.

But all of my date time objects turn into hierarchical object, instead of the string representation I need.

Before (OffsetDateTime):

  "date": "2000-04-26T10:10:00Z"

After deserializing, editing, and reserializing again:

"date":{
        "dateTime":{
          "date":{
            "year":2000,
            "month":1,
            "day":1
          },
          "time":{
            "hour":0,
            "minute":0,
            "second":0,
            "nano":0
          }
        },
        "offset":{
          "totalSeconds":0
        }
      }

And then my original code for serializing:

Gson gson = new GsonBuilder()
            .serializeNulls()             
            .create();

String json = gson.toJson(myObject);

I've tried all the solutions in this question: GSON - Date format But none of them change anything. I thought it was the same question, but now I think my problem is different. A lot has changed in java, since this question was asked in 2011.

Here are the concrete examples of lines I have tried to add to my GsonBuilder:

.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
...
.setDateFormat(DateFormat.LONG)
...
.setDateFormat(DateFormat.FULL, DateFormat.FULL)

And many more. None make any difference.

How can I get Gson to serialize different Java date objects as string representations?

jumps4fun
  • 3,994
  • 10
  • 50
  • 96
  • 1
    There’s no native supports for java.time classes in again. You’ll have to write your own serializers. – Sotirios Delimanolis Jan 02 '23 at 16:02
  • 2
    I have not used the Gson library; but looking at the JSON, it seems this is how Gson structures a date-time. A simple solution can be creating a new field/attribute and writing the value of `OffsetDateTime::toString` or the value of `OffsetDateTime::format` (for formatted value) to it. – Arvind Kumar Avinash Jan 02 '23 at 16:02

1 Answers1

0

After reading the comments on the question, stating that there are no native support for this on Gson, I decided to look to other libraries.

And I easily achieved my goal, using com.fasterxml.jackson.databind.ObjectMapper.java

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new JavaTimeModule())
    .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

json = mapper.writeValueAsString(myObject);
jumps4fun
  • 3,994
  • 10
  • 50
  • 96