@JsonSerialize和JsonSerializer的用法 [英] Usage of @JsonSerialize and JsonSerializer
问题描述
我有一个Spring MVC应用程序,它要求我将某个实体列表的id和名称转换为具有特定格式的JSON对象数组,并在某个请求上输出。也就是说,我需要一个像这样的JSON对象数组:
I have a Spring MVC application that requires me to translate the id's and names of a list of a certain entity to an array of JSON objects with specific formatting, and output that on a certain request. That is, I need an array of JSON objects like this:
{
label: Subject.getId()
value: Subject.getName()
}
为了便于jQuery使用自动完成插件。
For easy use with the jQuery Autocomplete plugin.
所以在我的控制器中,我写了以下内容:
So in my controller, I wrote the following:
@RequestMapping(value = "/autocomplete.json", method = RequestMethod.GET)
@JsonSerialize(contentUsing=SubjectAutocompleteSerializer.class)
public @ResponseBody List<Subject> autocompleteJson() {
return Subject.findAllSubjects();
}
// Internal class
public class SubjectAutocompleteSerializer extends JsonSerializer<Subject> {
@Override
public void serialize(Subject value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeStringField("label", value.getId().toString());
jgen.writeStringField("value", value.getName());
jgen.writeEndObject();
}
}
我回来的JSON,是Jackson推断的默认序列化。我的自定义序列化程序似乎完全被忽略了。显然问题是@JsonSerialize或JsonSerializer的使用不正确,但我无法在任何地方找到这些内容的正确用法。
The JSON I get back however, is the default serialization inferred by Jackson. My custom serializer seems to be completely ignored. Obviously the problem is incorrect usage of @JsonSerialize or JsonSerializer, but I could not find proper usage of these within context anywhere.
使用Jackson实现我想要的序列化的正确方法是什么?请注意,在这种情况下,实体仅以这种方式序列化是很重要的,并且在其他地方打开其他序列化
What is the proper way to use Jackson to achieve the serialization I want? Please note that it's important that the entities are only serialized this way in this context, and open to other serialization elsewhere
推荐答案
@JsonSerialize应该在被序列化的类而不是控制器上设置。
@JsonSerialize should be set on the class that's being serialized not the controller.
这篇关于@JsonSerialize和JsonSerializer的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!