@RestController单个端点的自定义序列化 [英] Custom serialization of single @RestController endpoint
问题描述
是否有一种方法(最好是某种类型的注释)为@RestController
中的单个端点注册自定义序列化程序?扩展bean并在其上放置@JsonSerialize
是一种选择,但是这需要一个非常无用的新bean类.我尝试了以下方法:
Is there a way (preferably some type of annotation) to register a custom serializer for a single endpoint in a @RestController
? Extending the bean and putting a @JsonSerialize
on it would be an option, but that demands an otherwise pretty useless new bean class. I tried the following:
@JsonSerialize(using = CustomSerializer.class)
@RequestMapping(value = "/some_endpoint/", method = RequestMethod.GET)
public SomeType someEndpoint() {
return someObject;
}
但是在这种情况下,@JsonSerialize
注释对Spring似乎没有任何意义.有替代方法还是额外的bean类是我唯一的选择?
But the @JsonSerialize
annotation doesn't appear to have any meaning to Spring in that context. Is there an alternative or is the extra bean class my only option?
推荐答案
您可以在要添加或忽略的属性以及要应用该视图的方法中使用@JsonView(View.Summary::class)
,例如:
You can use @JsonView(View.Summary::class)
in the attributes you want to add or ignore and in the method you want to apply that view, for example:
public class View {
public interface Summary
}
public class A{
@JsonView(View.Summary.class)
private String serialized = "",
private String notSerialized = ""}
,然后在控制器中:
@JsonView(View.Summary.class)
@GetMapping("/")
@ResponseBody
public A getA(){
return A()
}
如果要反转JsonView(对没有视图的属性进行序列化).您可以添加以下属性:spring.jackson.mapper.default-view-inclusion=true
If you want to reverse the JsonView (serialize the atributtes who doesnt have the view). you can add the following propertie: spring.jackson.mapper.default-view-inclusion=true
这篇关于@RestController单个端点的自定义序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!