问题
i want to change the date format in a json that is delivered by a java rest webservice, that is because the json have the dates like this: 2019-05-23T06:00:00Z[UTC] , so the client confuse the [UTC] with an array, because of the '[' and ']'
im using glassfish 5 ,jax-rs , jackson 2.9.4 databind, . i have tried to use @JsonSerialize(using = CustomXSerializer.class) in the model object and didn work, also @JsonFormat(shape= JsonFormat.Shape.STRING, pattern="MM-dd-yyyy",timezone="CET") in the Date property in the model object but again didnt work, its always showing [UTC]
my code:
package api;
import model.people;
import java.util.Date;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/helloworld")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class HelloWorldRest {
@GET
@Produces(MediaType.APPLICATION_JSON)
public people sayHello() {
people p=new people("pepe", "27",new Date());
return p;
}
}
the model object:
public class people {
private String nombre;
private String edad;
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="MM-dd-yyyy",timezone="CET")
public Date d;
public people(String pNombre,String pEdad,Date pD)
{ nombre=pNombre;
edad=pEdad;
d=pD;
}
.
.
//getters and setters
pom:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>
is there any way to change the format if the Date seralization in one spot for all the model objects? i would prefer that instead of creating custom serializer for each model object , thanks in advance
回答1:
I normally use a @Provider
to customize dates.
@Provider
public class AppObjectMapper implements ContextResolver<ObjectMapper> {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
static {
// .. other configuration for Jackson Object Mapper.
MAPPER.setDateFormat(df);
}
public AppObjectMapper() {
}
@Override
public ObjectMapper getContext(Class<?> type) {
return MAPPER;
}
}
回答2:
i found what my problem was, i needed to register jackson as the json provider in jersey , so it can be registered in the web.xml like this
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.jackson.JacksonFeature</param-value>
</init-param>
and using the dependency at the pom like this:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.x</version>
</dependency>
来源:https://stackoverflow.com/questions/56296558/how-to-customize-date-in-jackson-serialization-jsonserialize-not-working