在RESTful Api中,Response中字段JSON格式化

1、假设RESTful Api中,响应为如下代码所示。我们需要将UserResourcecreatedDate格式化为2021-11-11 11:11:00的格式,我们可以使用@JsonFormat注解。

  • 调整前
public class UserResource {
    private String firstName;
    private String lastName;
    private Date createdDate;

    // standard constructor, setters and getters
}
  • 调整后
public class UserResource {
    private String firstName;
    private String lastName;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createdDate;

    // standard constructor, setters and getters
}

2、如果需要返回的字段名从驼峰转成下划线可以使用@JsonProperty注解。例如我们将UserResourcefirstName字段在json中显示使用下划线first_name,则可以这样调整。

  • 调整前
public class UserResource {
    private String firstName;
    private String lastName;
    private Date createdDate;

    // standard constructor, setters and getters
}
  • 调整后
public class UserResource {
  @JsonProperty(value = "first_name")
    private String firstName;
    private String lastName;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createdDate;

    // standard constructor, setters and getters
}

你可能感兴趣的:(在RESTful Api中,Response中字段JSON格式化)