Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of @JsonSerialize and JsonSerializer

Problem

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.

Question

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

like image 688
DCKing Avatar asked Aug 08 '11 21:08

DCKing


1 Answers

@JsonSerialize should be set on the class that's being serialized not the controller.

like image 112
henrik_lundgren Avatar answered Oct 25 '22 13:10

henrik_lundgren