将实体类输出为指定格式(包含下划线,驼峰,大小写)

发布时间 2023-11-21 19:19:07作者: 北岛的樱花

一般的实体类字段命名规则基于驼峰命名规则,但是有时候需要调用实体类,需要返回指定的格式。如大小写、字母加下划线等格式。可以使用以下方法,快速生成指定的格式:(该项目为Springboot项目)

  • 准备一个实体类:
@Data
public class Test {
   private  String name;
   private  String workPlace;
   private  String workCardId;
}
  • 使用ObjectMapper类转换:
@GetMapping("/test")
   public String toJson() {
       try {
           Test test = new Test();
           test.setName("wangk");
           test.setWorkPlace("南京大学科创园");
           test.setWorkCardId("12345");

           ObjectMapper objectMapper = new ObjectMapper();
           objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
           String result =objectMapper.writeValueAsString(test);
           return result;
           
       } catch (JsonProcessingException e) {
           throw new RuntimeException(e);
       }
   }
  • 运行测试
    在这里插入图片描述

补充说明
案例:字段名workPlace,
LOWER_CASE:字段名均为小写字母,没有分隔符,例如 workplace。
KEBAB_CASE:字段名之间用连字符分隔,例如work-place。
LOWER_DOT_CASE:所有字母均为小写字母,用点连接字符,例如work.place
SNAKE_CASE:所有字母均为小写,并在名称元素之间使用下划线作为分隔符,例如 work_place
UPPER_CAMEL_CASE:所有名称元素,包括第一个,都以大写字母开头,后跟小写字母,并且没有分隔符,例如 WorkPlace。
LOWER_CAMEL_CASE:除第一个字母小写,其余为第一个字母为大写,中间没有连接符(小驼峰命名规则)例如:
workPlace