Spring and Jackson Json: serialising two different

2019-08-08 07:56发布

I've a Classified interface, annotated with @JsonAutoDetect with Visibility.NONE, so I can pick individual getters to be serialized with the @JsonSerialize annotation

@JsonAutoDetect(getterVisibility = Visibility.NONE)
public interface Classified {

    @JsonSerialize
    String getModel();

Until here there is no problem, and when I return Classified with @ResponseBody annotation, from my @Controller, it works returning the expected JSON:

    @RequestMapping(value = "/classified/{idClassified}", method = RequestMethod.GET)
    @ResponseBody
    public final Classified getClassified(@PathVariable final int idClassified) {

However when I return a List of Classifieds, I would like to return a smaller set of getters, while with the following signature, obviously it returns all marked getters:

@RequestMapping(value = "/classified", method = RequestMethod.GET)
@ResponseBody
public final List<Classified> searchClassified(@RequestParam final int idBrand,
    @RequestParam final String priceMax, @RequestParam final int page) {

I don't know how to return a smaller subset of Classified getters in each item of the list.

2条回答
倾城 Initia
2楼-- · 2019-08-08 08:39

Check out "filtering properties", which lists multiple ways to change what gets serialized. I would guess that Json Views might be the easiest one; could use one smaller view, and then default "all" mode when no view is defined (default is then to serialize all properties).

查看更多
We Are One
3楼-- · 2019-08-08 08:46

"return a smaller set of getters"

If you mean reduce the number of items in the list, change the business logic in the controller's searchClassified method.

If you mean reduce the number of available public getter methods on each item, you could create a interface that only implements a subset of the original items getters, and return a list of them instead.

查看更多
登录 后发表回答