美文网首页Java简友广场
在RESTful Api中,Response中字段JSON格式化

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

作者: 西安法律咨询服务平台与程序员 | 来源:发表于2021-11-24 13:41 被阅读0次

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格式化

    本文链接:https://www.haomeiwen.com/subject/vukntrtx.html