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
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@JsonPropertyon 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:
On the other hand per-field ignore scheme can be implemented the following way: