Note that there are some explanatory texts on larger screens.

plurals
  1. POUsage of @JsonSerialize and JsonSerializer
    primarykey
    data
    text
    <h3>Problem</h3> <p>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:</p> <pre><code>{ label: Subject.getId() value: Subject.getName() } </code></pre> <p>For easy use with the jQuery Autocomplete plugin.</p> <p>So in my controller, I wrote the following:</p> <pre><code>@RequestMapping(value = "/autocomplete.json", method = RequestMethod.GET) @JsonSerialize(contentUsing=SubjectAutocompleteSerializer.class) public @ResponseBody List&lt;Subject&gt; autocompleteJson() { return Subject.findAllSubjects(); } // Internal class public class SubjectAutocompleteSerializer extends JsonSerializer&lt;Subject&gt; { @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(); } } </code></pre> <p>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.</p> <h3>Question</h3> <p>What is the proper way to use Jackson to achieve the serialization I want? Please note that it's important that the entities are <em>only</em> serialized this way in this context, and open to other serialization elsewhere</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload