Use @JsonView to exclude (like @JsonIgnore) with play frameworks default json writer?

后端 未结 2 381
Happy的楠姐
Happy的楠姐 2021-01-24 03:16

It seems you can\'t mix @JsonIgnore and @JsonView. I want to hide a field by default, but show it in some cases.

Basically I\'ve got this setup :-

class         


        
2条回答
  •  佛祖请我去吃肉
    2021-01-24 03:58

    You may try JsonFilter in your child class you need to add this annotation @JsonFilter("myFilter")

    @JsonFilter("myFilter")     // myFilter is the name of the filter, you can give your own.
    class Child extends Model {
    
      public Long id;
      public String secret;
    }
    
    ObjectMapper mapper = new ObjectMapper();
    
    /* Following will add filter to serialize all fields except the specified fieldname and use the same filter name which used in annotation.
       If you want to ignore multiple fields then you can pass Set */
    
    FilterProvider filterProvider = new SimpleFilterProvider().addFilter("myFilter",SimpleBeanPropertyFilter.serializeAllExcept("secret"));
    mapper.setFilters(filterProvider);
    
    try {
        String json = mapper.writeValueAsString(child);    
    } catch (JsonProcessingException e) {
        Logger.error("JsonProcessingException ::: ",e);
    }
    
    If you dont want to ignore any field then, just pass empty string `SimpleBeanPropertyFilter.serializeAllExcept("")`
    

提交回复
热议问题