Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@JsonFormat not working in nested object

Tags:

java

json

spring

I have a very simple 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;
 }
}

And I wrap it in another bean that I use to wrap objects for nice json formatting with messages and stuff:

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

In my controller, I set the Status bean inside the response bean with a setData();

Spring serializes this out in JSON format, however the output for the date is not formatting. I am getting the standard "yyyy-MM-DD" format.

Am I doing something wrong? How do I get this to work?

like image 568
mmaceachran Avatar asked Aug 16 '26 10:08

mmaceachran


2 Answers

I had the same issue and fixed simply adding @JsonSerialize(as = Date.class) before @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")

like image 181
Luis Costa Avatar answered Aug 17 '26 23:08

Luis Costa


With @DateTimeFormat(pattern="dd/MM/yyyy") from org.springframework.format.annotation.DateTimeFormat worked for me.

like image 24
jaxonjma Avatar answered Aug 18 '26 01:08

jaxonjma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!