Reputation: 171
I need a help to convert a java object to json string without converting a LocalDateTime field to a separate object.
class MyObj {
LocalDateTime date;
}
then,
MyObj dateObj = new MyObj();
dateObj.date = LocalDateTime.now();
When I am converting it to a json,
Gson gson = new GsonBuilder().setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();
gson.toJson(dateObj);
I am getting this:
{
"date": {
"date": {
"year": 2020,
"month": 8,
"day": 27
},
"time": {
"hour": 8,
"minute": 59,
"second": 47,
"nano": 0
}
}
}
But I want this:
"date" : "2020-08-27T08:59:470Z"
Kindly help me about it.
Upvotes: 0
Views: 1342
Reputation: 171
I solved by this way.
Create a Gson object:
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();
Use method like this:
String jsonRequestString = gson.toJson(request);
Create a serializer:
class LocalDateAdapter implements JsonSerializer<LocalDate> {
@Override
public JsonElement serialize(LocalDate date, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
}
Upvotes: 1
Reputation: 3260
As per javadoc of setDateFormat
The date format will be used to serialize and deserialize {@link java.util.Date}, {@link java.sql.Timestamp} and {@link java.sql.Date}.
You need to register custom serializer for LocalDateTime.class
JsonSerializer<LocalDateTime> localDateTimeSerializer = (src, type, context) -> {
String date = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss").format(src);
// String date = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(src);
// String date = src.toString();
return new JsonPrimitive(date);
};
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, localDateTimeSerializer).create();
gson.toJson(dateObj);
Note: LocalDateTime doesn't store timezone information, so you can't actually use Z
in your date format pattern.
Upvotes: 0