首页 > 解决方案 > @JsonSerialize 没有从控制器 springboot 2.2.4 转换我的日期格式

问题描述

我有带日期的模型(ModelX)

@Entity
class ModelX
   ....
    @JsonSerialize(using = DateSerializer.class)
    private Long date;

日期序列化器

public class JsonDateSerializer extends JsonSerializer<DateTime>
{

private static DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");

@Override
public void serialize(DateTime value, JsonGenerator gen, 
                      SerializerProvider arg2)
    throws IOException, JsonProcessingException {

    gen.writeString(formatter.print(value));
}
}

我的控制器

@RestController
public class XC {

 @GetMapping(value = "/get/{main_key}"
 public get ModelX get(@PathVariable("main_key") String main_key) {
   return repository.get(main_key);
 }

}

提取有效,但我的日期很长,但我想要一个日期“dd/MM/yyyy”

标签: javaspring-bootdatetime-format

解决方案


使用 JSON 自定义序列化程序,您可以格式化 LONG 日期

@Entity
class ModelX
   ....
    @JsonSerialize(using = JsonDateCustom.class)
    private Long date;

自定义序列化器

@Component
public class JsonDateCustom extends JsonSerializer<Long> {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String formattedDate = dateFormat.format(value);
        gen.writeString(formattedDate);

    }
}

推荐阅读