在 Spring Boot 中实现 JSON 字段的蛇形命

在 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技术服务公司-木风未来科技-成都木风未来科技有限公司

相关推荐
钟离墨笺19 小时前
Go语言-->interfance{}赋值的陷阱
开发语言·后端·golang
阿杰真不会敲代码20 小时前
POI 讲解
java·spring boot
+VX:Fegn089521 小时前
计算机毕业设计|基于springboot + vue校园跑腿系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
VX:Fegn089521 小时前
计算机毕业设计|基于springboot + vue在线考试系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
二哈喇子!21 小时前
springboot项目运行时报错:HikariPool-1 - Exception during pool initialization.
java·spring boot·spring
且去填词1 天前
Go 内存分配器(TCMalloc):栈与堆的分配策略
开发语言·后端·面试·golang
天草二十六_简村人1 天前
ES索引检索课程名称时,同时支持模糊搜索和精准搜索
大数据·后端·elasticsearch·搜索引擎·全文检索
白露与泡影1 天前
SpringBoot + Vue 实现 Python 在线调试器 - 技术方案文档
vue.js·spring boot·python
阿杰真不会敲代码1 天前
webSocket入门
java·网络·spring boot·websocket·网络协议
天若有情6731 天前
详解Two Pair函数:「一次握手,一次挥手」,让函数调用更严谨、更安全
网络·c++·后端·安全·设计