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

使用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);
}
}

最新更新