jackson 如何在Spring中从JSON响应中过滤属性?

ddrv8njm  于 2022-11-09  发布在  Spring
关注(0)|答案(4)|浏览(146)

我有一个如下所示的控制器,

@RequestMapping(value = "rest/v1/tester")
public class TestController {

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ResponseEntity<SampleResults> search(@ModelAttribute("criteria")SampleCriteria criteria) throws Exception {
            SampleResults sampleResults = sampleService.search(criteria);
            return new ResponseEntity<>(sampleResults, OK);
    }

}

我有另一个类似的控制器,

@RequestMapping(value = "rest/v1/second")
public class SecondTestController {

@RequestMapping(value = "/search", method = RequestMethod.GET)
    public ResponseEntity<SampleResults> search(@ModelAttribute("criteria")SampleCriteria criteria) throws Exception {
            SampleResults sampleResults = secondsampleService.search(criteria);
            return new ResponseEntity<>(sampleResults, OK);
    }

}

我的结果的结构如下:

public class SampleResults extends Results<SearchSummary, Sample> {
}

这是从结果类扩展而来的:

public class Results<SUMMARY,RESULTS> {
    private SUMMARY summary;
    private List<RESULTS> results;

    /*Constructors, getters and setters*/
}

现在我要在结果字段中设置的模型是,

@JsonDeserialize(as = SampleImpl.class)
public interface Sample {

    Long getId();
    void setId(Long id);

    String getName();
    void setName(String name);

    int getAge();
    void setAge(int age);

}

public class SampleImpl implements Sample {

    private Long id;
    private String name;
    private int age;

    /* Getters and Setters */

}

现在对于上面提到的TestController,我想显示json响应中的所有字段,而在SecondTestController中,我想屏蔽(不显示)json响应中的age属性。我如何在Spring中实现这一点?非常感谢您的帮助!

yuvru6vn

yuvru6vn1#

我认为最简单的方法是使用Jackson @JsonFilter,如果您希望它是动态的。
例如,以下是Spring Boot的一个示例:
您的文件:

@JsonFilter("myFilter")
class Document {
   private field1;
   private field2;
}

修改默认配置的HttpMessageConverter:

@Configuration
class WebMvcConfiguration extends WebMvcConfigurationSupport {
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for(HttpMessageConverter<?> converter: converters) {
            if(converter instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper mapper = ((MappingJackson2HttpMessageConverter)converter).getObjectMapper();
                mapper.setFilterProvider(new SimpleFilterProvider().addFilter("myFilter", SimpleBeanPropertyFilter.serializeAll()));
            }
        }
    }
}

默认情况下,这个过滤器将序列化所有对象。这一步是强制性的,如果你不指定它,当你的控制器试图生成一个对象响应时,你会遇到一个异常,即他不知道myFilter
然后,在您的控制器中,这里是您的常规端点,它序列化所有字段(使用前面声明的过滤器):

@RequestMapping(value = "path/document", method = RequestMethod.GET)
public Document getDocumentWithAllFields() {
   return new Document("val1","val2");
} 
//result : {"field1":"val1","field2":"val2"}

而现在,端点对具有相同对象的对象只序列化了一些字段:

@RequestMapping(value = "path/document", method = RequestMethod.GET)
public MappingJacksonValue getDocumentWithSomeFields(@RequestParam String[] fields) {
    MappingJacksonValue wrapper = new MappingJacksonValue(new Document("val1","val2"));
    FilterProvider filterProvider = new SimpleFilterProvider().addFilter("myFilter", 
         SimpleBeanPropertyFilter.filterOutAllExcept(fields)); 
    wrapper.setFilters(filterProvider);
    return wrapper;
} 
//result : {"field1":"val1"} (with 'fields' being a coma separated list, containing here just "field1"
polhcujo

polhcujo2#

您考虑过@JsonView吗?
它是supported by Spring MVC,允许您根据序列化的上下文筛选字段。
首先定义视图:

public class View {     

    interface SampleView { }  
    interface SampleViewWithAge extends SampleView { }   
}

然后使用所需视图注解字段:

public class SampleImpl implements Sample { 

    @JsonView(View.SampleView.class)
    private Long id; 

    @JsonView(View.SampleView.class)
    private String name; 

    @JsonView(View.SampleViewWithAge.class)
    private int age;

    // Getters and setters
 }

最后,对处理程序进行注解,以便在序列化响应时使用视图:

@JsonView(View.SampleView.class) 
@RequestMapping(value = "/search", method = RequestMethod.GET)  
public ResponseEntity<SampleResults> search() {
    ... 
}

@JsonView(View.SampleViewWithAge.class)
@RequestMapping(value = "/search", method = RequestMethod.GET)  
public ResponseEntity<SampleResults> searchWithAge() {
    ... 
}
cfh9epnr

cfh9epnr3#

使用必需字段覆盖模态类中的toString方法,并在第二个控制器方法中将其显式转换为json,如下所示。

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
//get yourObject

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(yourObject);
irtuqstp

irtuqstp4#

公共类BeanFilterCustom {

public Object filterBean(Object object,String someBeanFilter)  {

    SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("","");
    FilterProvider filters = new SimpleFilterProvider()
            .addFilter(someBeanFilter, filter);
    MappingJacksonValue mapping = new MappingJacksonValue(object);
    mapping.setFilters(filters);
    return mapping.getValue();
}

}

相关问题