1

I have a spring controller return an entity in json. The entity contains a date and I want to return EITHER 12hours format OR 24hours format according to one field in the entity. Does Spring or jackson provides such kind of feature?

@RequestMapping(value = "/{systemName}",method = RequestMethod.GET)
public Entity getEntityByName(@PathVariable String name,HttpServletResponse response){
Entity entity = service.getEntity(name);
    if(entity ==null){
        response.setStatus(404);
    }
    return entity ;

}
Dong Hang
  • 9
  • 5

2 Answers2

2

In Jackson 2 and above

@JsonFormat(shape = JsonFormat.Shape.STRING ,pattern = "dd-MM-YYYY hh:mm:ss" , timezone="UTC")
private Date from_date;
Vaibs
  • 1,546
  • 9
  • 31
  • This only changeS the date pattern to dd-MM-YYYY hh:mm:ss, whereas I needed it to be configurable into different patterns. – Dong Hang May 01 '17 at 21:11
  • Refer http://stackoverflow.com/questions/18734452/display-current-time-in-12-hour-format-with-am-pm. you need to change the pattern. – Vaibs May 04 '17 at 14:06
0

In short, yes this is possible. With that said, I would encourage you to return a numeric representation of the date and leave it up to your consumers to display it however they want. Here is a means for achieving what you want.

Create a class that will serve as the Serializer for the Entity Object.

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

public class EntitySerializer extends JsonSerializer<Entity> {
   @Override
   public void serialize(Entity entity, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {

       jsonGenerator.writeStartObject();
       jsonGenerator.writeStringField("name", entity.getName());

       if (entity.getFieldThatIndicates24HourFormat()) {
          jsonGenerator.writeStringField("date", entity.getDate().toString());
       } else {
          jsonGenerator.writeStringField("date", entity.getDate().toString());
       }

       jsonGenerator.writeEndObject();
   }
}

On your Entity, add an annotation that will enable this class to be used for serializing it.

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@JsonSerialize(using = EntitySerializer.class)
public class Entity {

There are obvious pitfalls with this, as you now will have to be mindful of changes to your Entity and update the serializer accordingly.

lane.maxwell
  • 5,002
  • 1
  • 20
  • 30