我有一个非常简单的bean:
public class StatusBean {
private String name;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
private Date startDate;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
private Date endDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
我将它包装在另一个bean中,我用它来包装对象以获得带有消息和东西的漂亮的json格式:
public class ResponseBean {
private boolean success = false;
private String message;
private Object data;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
在我的控制器中,我使用setData();
在Status bean中设置Status beanSpring以JSON格式将其序列化,但日期的输出不是格式化。我正在获得标准" yyyy-MM-DD"格式。
我做错了吗?我如何让它工作?
答案 0 :(得分:2)
我遇到了同样的问题,并修复了在@JsonSerialize(as = Date.class)
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
的问题
答案 1 :(得分:1)
我从未尝试过,但解决方案可能是在ResponseBean中添加此注释:
@JsonSerialize(as = StatusBean.class)
private Object data;
不幸的是,您的Object将成为StatusBean
答案 2 :(得分:0)
来自@DateTimeFormat(pattern="dd/MM/yyyy")
org.springframework.format.annotation.DateTimeFormat
为我工作。
答案 3 :(得分:0)
可能无法使用 ObjectMapper
写入对象new ObjectMapper().writeValueAsString(MyObject);
完整代码示例
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(new Foo(new java.util.Date())));
System.out.println(objectMapper.writeValueAsString(new Foo(new java.sql.Date(System.currentTimeMillis()))));
}
static class Foo {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy", timezone="EST")
private Date birthdate;
public Foo() {
}
public Foo(Date birthdate) {
this.birthdate = birthdate;
}
public Date getBirthdate() {
return birthdate;
}
}