Spring 3.1.1 web MVC - limit response to interface geters

jackson, java, spring, spring-mvc

Solution

If I understand your question correctly and you are using Jackson for convert result to JSON, then you can use org.codehaus.jackson.annotate.JsonIgnore to avoid the field to be polupated into JSON result. (Henry) Furthermore, it is possible to add to the interface `@JsonAutoDetect(JsonMethod.NONE)` which would cause Jackson not to search automatically for fields to serialize and then add `@JsonProperty` on the fields that are indeed needed for serialization (virtually implementing a white list scheme for the Jackson field serialization strategy).

Here is the sample code which solves the above problem:

@JsonAutoDetect(JsonMethod.NONE) //This tells the json serializer not to search for properties to serialize
public interface VODAsset {
    @JsonProperty //This tells the json serializer that this is a property that it should serialize
    public String getName();
}

On the other hand per-field ignore scheme can be implemented the following way:

Marker annotation that indicates that the annotated method or field is to be ignored by introspection-based serialization and deserialization functionality. That is, it should not be consider a "getter", "setter" or "creator".

@JsonIgnore
public String getId() {
    return id;
}

Problem

The following is a snippet from a project based on Spring web MVC 3.1.1. Json serialization is made via Jackson. I have a controller which is mapped to a URL and everything is working fine. ``` @Controller @RequestMapping("/vod") public class VODController { private Configuration configuration; private SearchAPI searchAPI; @RequestMapping(method = RequestMethod.GET, params = "cmd=list") public @ResponseBody GetAssetsReply listVODAssets(long offset, int limit) { SearchVODAssetRequest searchVODAssetRequest = new SearchVODAssetRequest(); //.... some irrelevant code return searchAPI.searchVODAssets(searchVODAssetRequest); } } ``` And this is `GetAssetsReply`: ``` public class GetAssetsReply { private long totalAssets; private List<VODAsset> assets = new LinkedList<VODAsset>(); // Getters and setters removed for simplicity } ``` `VODAsset` is an interface: ``` public interface VODAsset { public String getName(); } ``` And this is its implementation: ``` public class AssetElement implements VODAsset { private String id; private String name; private double duration; // Getters and setters removed for simplicity } ``` Finally to the question: The controller returns me the expected result with one down side - It returns the VOD assets with its ID and duration in addition to its name. What I would expect is to get only the name due to the fact that the object is pointed by the above `VODAsset` interface. How can I get this behavior? Any help would be much appreciated

Original source