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()
}
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();
}
}
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.
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
should be set on the class that's being serialized not the controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With