You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过注解让RestController输出带缩进的格式化JSON?

单个Spring Boot RestController实现带缩进的JSON输出

要针对单个RestController类实现格式化缩进的JSON输出,且不影响全局配置,有以下几种可行方案:

方案一:手动使用配置好缩进的ObjectMapper序列化

在目标Controller中创建一个开启了INDENT_OUTPUT特性的ObjectMapper,在接口方法中手动将对象序列化为带缩进的JSON字符串返回:

@RestController
@RequestMapping(value = "/custom-api", produces = MediaType.APPLICATION_JSON_VALUE)
public class CustomIndentedController {

    private final ObjectMapper indentedObjectMapper;

    // 初始化时配置缩进输出
    public CustomIndentedController() {
        indentedObjectMapper = new ObjectMapper();
        indentedObjectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    }

    @GetMapping("/user")
    public String getIndentedUser() throws JsonProcessingException {
        User user = new User("John", "Doe", 30);
        return indentedObjectMapper.writeValueAsString(user);
    }
}

这种方式简单直接,完全控制单个Controller的序列化行为,无需额外全局配置。

方案二:使用ControllerAdvice针对单个类配置

通过@RestControllerAdvice指定作用的Controller类,在Advice中修改ObjectMapper的序列化特性,实现专属的缩进输出:

// 仅对CustomIndentedController生效的Advice
@RestControllerAdvice(assignableTypes = CustomIndentedController.class)
public class IndentedJsonAdvice extends AbstractMappingJacksonResponseBodyAdvice {

    @Override
    protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, 
                                          MediaType contentType, 
                                          MethodParameter returnType,
                                          ServerHttpRequest request, 
                                          ServerHttpResponse response) {
        // 开启缩进输出特性
        bodyContainer.getObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
    }
}

这种方案符合Spring注解式编程风格,不需要在接口方法中手动序列化,保持Controller方法返回对象的习惯。

关于@JsonSerialize的说明

你提到的@JsonSerialize注解主要用于指定自定义序列化器,处理特定字段或对象的序列化逻辑,无法直接配置JSON的缩进格式,因此不适用这个场景。

内容的提问来源于stack exchange,提问作者Y'Kotyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:55:25