在Spring Boot的Jackson中我们可以使用@JsonProperty对Java属性转Json字符串的key进行指定。那么,当批量处理统一类型的格式时,@JsonProperty就显得比较麻烦了。

public class LoginUser {

    @JsonProperty("user_name")
    private String username;
}

那么,针对此问题,可以使用Jackson命名策略来进行解决。比如所有属性都是基于驼峰标识,需要转化为以下划线“_”进行分割,那么就可以使用@JsonNaming来统一策略指定。

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class UserDetail {

}

这样,该类下的所有属性在转化为Json字符串时,均会将驼峰标识转化为以下划线“_”进行分割。

其中在PropertyNamingStrategy中,提供了多重策略。

  • SNAKE_CASE:示例“userName”转化为“user_name”。
  • UPPER_CAMEL_CASE:示例“userName”转化为“UserName”。
  • LOWER_CAMEL_CASE:默认模式,示例“userName”转化为“userName”。
  • LOWER_CASE:示例“userName”转化为“username”。
  • KEBAB_CASE:示例“userName”转化为“user-name”。
  • LOWER_DOT_CASE:示例“userName”转化为“user.name”。

CSDN学院:《Spring Boot 视频教程全家桶》



Spring Boot Jackson命名策略插图

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.choupangxia.com/2020/01/02/spring-boot-jackson/