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 ;

}
1
  • How is the code sample related to your question? Commented Apr 26, 2017 at 19:47

2 Answers 2

2

In Jackson 2 and above

@JsonFormat(shape = JsonFormat.Shape.STRING ,pattern = "dd-MM-YYYY hh:mm:ss" , timezone="UTC")
private Date from_date;
Sign up to request clarification or add additional context in comments.

2 Comments

This only changeS the date pattern to dd-MM-YYYY hh:mm:ss, whereas I needed it to be configurable into different patterns.
Refer stackoverflow.com/questions/18734452/…. you need to change the pattern.
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.

1 Comment

Thanks! this is really helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.