全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-18 6 分钟 ✍️ juanwangdev

SpringBoot项目JSON交互

SpringBoot 默认集成 Jackson 作为 JSON 处理框架。

基本使用

Controller返回JSON

Java
@RestController
public class UserController {

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }

    @PostMapping("/users")
    public User createUser(@RequestBody UserDTO dto) {
        return userService.save(dto);
    }
}

JSON自动转换

Java
@Data
public class User {
    private Long id;
    private String username;
    private String email;
    private Date createTime;
}

// 输出JSON
{
    "id": 1,
    "username": "张三",
    "email": "test@example.com",
    "createTime": "2026-05-18T10:30:00.000+00:00"
}

Jackson配置

YAML
spring:
  jackson:
    # 日期格式
    date-format: yyyy-MM-dd HH:mm:ss
    # 时区
    time-zone: GMT+8
    # 格式化输出
    default-property-inclusion: non_null
    # 序列化配置
    serialization:
      write-dates-as-timestamps: false
      fail-on-empty-beans: false
    # 反序列化配置
    deserialization:
      fail-on-unknown-properties: false

常用注解

Java
@Data
public class UserDTO {

    // 忽略字段
    @JsonIgnore
    private String password;

    // 自定义字段名
    @JsonProperty("user_name")
    private String username;

    // 格式化日期
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date birthday;

    // 包含条件
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String nickname;

    // 字段顺序
    @JsonPropertyOrder(alphabetic = true)
    private Map<String, Object> extra;

    // 自定义序列化
    @JsonSerialize(using = CustomSerializer.class)
    private Status status;
}

自定义序列化器

Java
public class CustomDateSerializer extends JsonSerializer<Date> {

    private static final SimpleDateFormat format =
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void serialize(Date value, JsonGenerator gen,
                          SerializerProvider provider) throws IOException {
        gen.writeString(format.format(value));
    }
}

// 使用
@JsonSerialize(using = CustomDateSerializer.class)
private Date createTime;

自定义反序列化器

Java
public class CustomDateDeserializer extends JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctx)
            throws IOException {
        String dateStr = p.getValueAsString();
        try {
            return new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
        } catch (ParseException e) {
            throw new RuntimeException("日期格式错误");
        }
    }
}

// 使用
@JsonDeserialize(using = CustomDateDeserializer.class)
private Date birthday;

全局配置类

Java
@Configuration
public class JacksonConfig {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer() {
        return builder -> {
            builder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
            builder.timeZone(TimeZone.getTimeZone("GMT+8"));
            builder.featuresToDisable(
                SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
            );
            builder.featuresToEnable(
                SerializationFeature.WRITE_ENUMS_USING_TO_STRING
            );
            builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        };
    }
}

枚举处理

Java
public enum Status {
    ACTIVE("激活"),
    INACTIVE("禁用"),
    DELETED("删除");

    private final String description;

    @JsonValue  // 序列化时输出description
    public String getDescription() {
        return description;
    }
}

// 或使用toString
@JsonFormat(shape = JsonFormat.Shape.STRING)
public enum Type {
    ADMIN, USER, GUEST
}

忽略空值配置

配置值说明
ALWAYS总是包含
NON_NULL非null才包含
NON_EMPTY非空才包含
NON_DEFAULT非默认值才包含
Java
// 单字段配置
@JsonInclude(JsonInclude.Include.NON_NULL)
private String remark;

// 全局配置
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class UserDTO {
    // 所有字段都应用此规则
}

集合处理

Java
@GetMapping("/users")
public List<User> getUsers() {
    return userService.findAll();
}

// 输出
[
    {"id": 1, "name": "张三"},
    {"id": 2, "name": "李四"}
]

// Map处理
@GetMapping("/stats")
public Map<String, Integer> getStats() {
    Map<String, Integer> stats = new HashMap<>();
    stats.put("total", 100);
    stats.put("active", 80);
    return stats;
}

要点总结

  • SpringBoot默认使用Jackson处理JSON
  • 配置spring.jackson.*调整序列化行为
  • @JsonProperty自定义字段名
  • @JsonFormat格式化日期类型
  • @JsonIgnore忽略敏感字段

📝 发现内容有误?点击此处直接编辑

← 上一篇 SpringBoot快速创建WEB项目
下一篇 → SpringBoot Maven与Gradle构建工具
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库