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?