在 Spring Boot 项目中,常常需要实现 Java 对象字段使用驼峰命名,而在序列化为 JSON 时使用蛇形命名。这种需求在与外部 API 交互或满足特定数据格式规范时尤为常见。本文将详细介绍几种实现方案,并提供代码示例。

方案一:全局配置(推荐)

通过修改 `application.properties` 或 `application.yml` 文件,为整个项目统一配置命名策略。

application.properties:

```properties

spring.jackson.propertynamingstrategy=SNAKE_CASE

```

application.yml:

```yaml

spring:

 jackson:

   propertynamingstrategy: SNAKE_CASE

```

优点:配置简单,一劳永逸,确保整个项目命名风格统一。

方案二:使用注解配置

在实体类上使用 `@JsonNaming` 注解,指定命名策略。

```java

import com.fasterxml.jackson.databind.PropertyNamingStrategies;

import com.fasterxml.jackson.databind.annotation.JsonNaming;

import lombok.Data;

@Data

@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)

public class User {

   private String userName;        // Java字段:驼峰命名

   private Integer userAge;

   private String emailAddress;

   // 序列化后JSON:{"user_name":"张三","user_age":25,"email_address":"zhangsan@example.com"}

}

```

方案三:自定义 Jackson 配置类

创建配置类,自定义 `ObjectMapper` Bean。

```java

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.databind.PropertyNamingStrategies;

@Configuration

public class JacksonConfig {

   @Bean

   public ObjectMapper objectMapper() {

       ObjectMapper objectMapper = new ObjectMapper();

       objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);

       return objectMapper;

   }

}

```

方案四:单个字段自定义映射

若仅需对部分字段使用蛇形命名,可在字段上使用 `@JsonProperty` 注解。

```java

import com.fasterxml.jackson.annotation.JsonProperty;

public class User {

   @JsonProperty("user_name")

   private String userName;

@JsonProperty("user_age")

   private Integer userAge;

private String emailAddress;  // 此字段将遵循默认命名策略

// 省略 getter 和 setter

}

```

优先级说明:字段级别的 `@JsonProperty` 注解优先级最高,会覆盖类级别或全局的命名策略。

完整示例

以下是一个完整的 API 响应封装示例,演示如何在实际项目中使用蛇形命名。

实体类(ApiResponse.java):

```java

import com.fasterxml.jackson.databind.PropertyNamingStrategies;

import com.fasterxml.jackson.databind.annotation.JsonNaming;

import java.sql.Timestamp;

@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)

public class ApiResponse<T> {

   private Integer code;

   private String message;

   private T data;

   private Timestamp createTime;

   // 构造方法、getter、setter 省略

}

```

控制器(UserController.java):

```java

import org.springframework.web.bind.annotation.;

@RestController

@RequestMapping("/api/users")

public class UserController {

@GetMapping("/{id}")

   public ApiResponse<User> getUser(@PathVariable Long id) {

       User user = new User();

       user.setUserName("张三");

       user.setUserAge(25);

       user.setEmailAddress("zhangsan@example.com");

       

       ApiResponse<User> response = new ApiResponse<>();

       response.setCode(200);

       response.setMessage("成功");

       response.setData(user);

       response.setCreateTime(new Timestamp(System.currentTimeMillis()));

       

       return response;

   }

}

```

响应结果(JSON):

```json

{

   "code": 200,

   "message": "成功",

   "data": {

       "user_name": "张三",

       "user_age": 25,

       "email_address": "zhangsan@example.com"

   },

   "create_time": "20231001T10:30:00.000+00:00"

}

```

注意事项

1.  优先级顺序:`@JsonProperty`(字段级)> `@JsonNaming`(类级)> 全局配置。

2.  反序列化支持:上述配置同样支持将蛇形命名的 JSON 数据反序列化为驼峰命名的 Java 对象。

3.  版本兼容性:不同 Spring Boot 版本可能在 Jackson 配置上略有差异,建议使用较新版本以获得更好的兼容性。

4.  一致性建议:为避免混淆和维护困难,推荐在项目中采用方案一的全局配置,确保所有 JSON 序列化行为保持一致。

通过以上任一种方案,均可轻松实现 Java 对象字段(驼峰命名)与 JSON 字段(蛇形命名)之间的优雅映射,满足不同场景下的数据格式需求。

来源:小程序app开发|ui设计|软件外包|IT技术服务公司-木风未来科技-成都木风未来科技有限公司

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐