gpt4 book ai didi

json - 根据 Jackson 和 Spring boot 的请求美化(或不美化)响应

转载 作者:行者123 更新时间:2023-12-01 15:40:43 26 4
gpt4 key购买 nike

我正在使用 Spring boot、Spring MVC 和 Jackson。我正在编写一个 RESTful API,其中一个要求是在请求包含参数 prettify 的情况下美化响应 (json)。

例如,GET/examples/1 必须回答:{"id":1,"name":"example"},和 GET/examples/1?prettify 使用:

{
"id": 1,
"name": "example"
}

我知道我可以定义我自己的 ObjectMapper 但我不能根据请求来实现。我可以将 spring.jackson.serialization.INDENT_OUTPUT 设置为 true 但我无法显示响应 not 美化。

有人对此有想法吗?

最佳答案

好的,我做到了。

所以,方法是使用注入(inject)的 Jackson2ObjectMapper 手动序列化响应:)

让我们看一下简单的主应用程序类:

@SpringBootApplication
public class StackoverflowApplication {

public static void main(String[] args) {
SpringApplication.run(StackoverflowApplication.class, args);
}

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true);
return builder;
}
}

一些休息 Controller 类:

@RestController
public class TestRestController {
private static final Logger LOGGER = Logger.getLogger(TestRestController.class);

@Autowired
Jackson2ObjectMapperBuilder objectMapperBuilder;

@RequestMapping(value = "/testendpoint/{somevalue}", method = RequestMethod.GET, produces="application/json")
public @ResponseBody String customersLastVisit(@PathVariable(value = "somevalue") Integer number,
@RequestParam(value = "pretify", defaultValue = "false") Boolean pretify) throws JsonProcessingException {
if (pretify) {
LOGGER.info("Pretify response!");
objectMapperBuilder.indentOutput(true);
}
else {
objectMapperBuilder.indentOutput(false);
}

ObjectMapper mapper = objectMapperBuilder.build();
String jsonResponse = mapper.writeValueAsString(new TestDTO());
return jsonResponse;
}
}

和 DTO 类:

public class TestDTO implements Serializable {

private static final long serialVersionUID = 1L;

private Integer id;
private String name;

public TestDTO() {
super();
id = new Integer(1);
name = new String("SomeName");
}
//getters, setters etc ...
}

http://localhost:8080/testendpoint/1返回 {"id":1,"name":"SomeName"}同时http://localhost:8080/testendpoint/1?pretify=true返回

{
"id" : 1,
"name" : "SomeName"
}

编辑:如果您想将它用于每个 Controller ,请执行以下操作:

public class PretifyingInterceptor extends HandlerInterceptorAdapter {

private static final Logger LOGGER = Logger.getLogger(PretifyingInterceptor.class);

@Autowired
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {

String pretify = request.getParameter("pretify");
Boolean isPretify = Boolean.parseBoolean(pretify);

LOGGER.info("Should be pretified: " + isPretify);

if (isPretify) {
mappingJackson2HttpMessageConverter.setPrettyPrint(true);
}
else {
mappingJackson2HttpMessageConverter.setPrettyPrint(false);
}
return true;
}
}

现在添加新的拦截器:

@Configuration
public class InterceptorConfigurerAdapter extends WebMvcConfigurerAdapter{


@Bean
PretifyingInterceptor pretifyingInterceptor() {
return new PretifyingInterceptor();
}

@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(pretifyingInterceptor())
.addPathPatterns("/**");
}

}

现在 Controller 看起来像:

@RequestMapping(value = "/testendpoint/{somevalue}", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody TestDTO customersLastVisit(@PathVariable(value = "somevalue") Integer number,
@RequestParam(value = "pretify", defaultValue = "false") Boolean pretify) throws JsonProcessingException {
return new TestDTO();
}

Edit2:为了避免一些“拦截器的请求间共享状态”,定义具有范围 request 的拦截器 bean。

希望对您有所帮助:)

关于json - 根据 Jackson 和 Spring boot 的请求美化(或不美化)响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35255667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com