When creating a Web API in Java, the date type such as LocalDateTime type is displayed in the response.
2019-01-01T01:00:00
Solution if it becomes like
--Create a serialized adapter --Create package-info.java in the package with the response model and load the created adapter
Create an adapter
LocalDateAdapter.java
package api.adapters;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class LocalDateAdapter extends XmlAdapter<String, LocalDate> {
@Override
public LocalDate unmarshal(String s) throws Exception {
if (s == null) {
return null;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(s, formatter);
return dateTime;
}
@Override
public String marshal(LocalDate d) throws Exception {
if (d == null) {
return null;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDateTime = d.format(formatter);
return formattedDateTime;
}
}
LocalDateTimeAdapter.java
package api.adapters;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {
@Override
public LocalDateTime unmarshal(String s) throws Exception {
if (s == null) {
return null;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(s, formatter);
return dateTime;
}
@Override
public String marshal(LocalDateTime d) throws Exception {
if (d == null) {
return null;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = d.format(formatter);
return formattedDateTime;
}
}
Read with package-info
package-info.java
//Annotate the adapter
@XmlJavaTypeAdapters(value = { @XmlJavaTypeAdapter(value = LocalDateTimeAdapter.class, type = java.time.LocalDateTime.class),
@XmlJavaTypeAdapter(value = LocalDateAdapter.class, type = java.time.LocalDate.class) })
package api.model.response;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
//Import adapter
import api.adapters.LocalDateAdapter;
import api.adapters.LocalDateTimeAdapter;
Recommended Posts