【问题标题】:Spring controller return different date formatSpring 控制器返回不同的日期格式
【发布时间】:2017-04-26 15:29:14
【问题描述】:

我有一个弹簧控制器以 json 格式返回一个实体。该实体包含一个日期,我想根据实体中的一个字段返回 12 小时格式或 24 小时格式。 Spring或jackson是否提供这种功能?

@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 ;

}

【问题讨论】:

  • 代码示例与您的问题有何关联?

标签: java json spring-mvc date-format


【解决方案1】:

在杰克逊 2 及更高版本中

@JsonFormat(shape = JsonFormat.Shape.STRING ,pattern = "dd-MM-YYYY hh:mm:ss" , timezone="UTC")
private Date from_date;

【讨论】:

【解决方案2】:

简而言之,是的,这是可能的。话虽如此,我鼓励您返回日期的数字表示形式,并将其留给您的消费者以他们想要的方式显示。这是实现您想要的方法的方法。

创建一个类,作为实体对象的序列化器。

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();
   }
}

在您的实体上,添加一个注释,使此类能够用于序列化它。

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

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

这有明显的缺陷,因为您现在必须注意对实体的更改并相应地更新序列化程序。

【讨论】:

  • 谢谢!这真的很有帮助!
猜你喜欢
  • 2014-04-10
  • 1970-01-01
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2012-02-29
相关资源
最近更新 更多