我有一个实体(使用lombok)和一些带注释的@JsonView注释。
@Entity
@Table(name = "`order`")
@Getter
@Setter
@ToString
@Description("Приказ")
public class Order extends Auditable {
private static final long serialVersionUID = -1299630493411381582L;
@JsonView(JsonViews.OrderAdvancedSearch.class)
@ManyToOne
private School school;
@Column(length = 50)
private String number;
}
有一个用@JsonView注释注释的控制器方法。
@Secured(value = {"ROLE_AUTHENTICATED_USER"})
@RequestMapping(value = "/order", method = RequestMethod.GET, headers = {"Content-Type=application/json"})
@JsonView(JsonViews.OrderAdvancedSearch.class)
@ResponseBody
public ResponseEntity<Order> getOrder(HttpServletRequest request) throws IOException, DnevnikException, RestException {
Order order = orderRepository.findOne(292L); // just for example
return new ResponseEntity<>(order,HttpStatus.OK);
}
我预计输入将只包含用@JsonView注释的字段。 但我充满了各种各样的领域。
我正在尝试调试spring和jackson来源。 在com.fasterxml.jackson.databind.SerializationConfig中,我看到活动视图是我的类JsonViews.OrderAdvancedSearch.class 但是在com.fasterxml.jackson.databind.ser.std.BeanSerializerBase变量中,filteredProps总是具有我实体的所有属性。
答案 0 :(得分:2)
尝试调整Jackson对象映射器:
// disable this feature so that attributes with no view definition
// do not get serialized / deserialized
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
答案 1 :(得分:2)
@Attila T的答案已经足够,但我已经发布了如何调整对象映射器并在任何地方使用它的代码
控制器代码:
@Autowired
JSONMapper objectMapper;
@RequestMapping
public ResponseEntity<> getSchoolDetails(ParameterMapper mapper,HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException
{
Order order = orderRepository.findOne(292L);
ObjectWriter w = objectMapper.writerWithView(SomeClass.class);
objectWriter.writeValue(response.getWriter(),order);
return new ResponseEntity<>(order,HttpStatus.OK);
}
自定义对象映射器
@Component
public class JSONMapper extends ObjectMapper {
public JSONMapper() {
Hibernate4Module hm = new Hibernate4Module();
registerModule(hm);
configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
configure(SerializationFeature.INDENT_OUTPUT , false);
configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
setSerializationInclusion(Include.NON_EMPTY);
}
}
调度程序配置(相应地更改基于xml的配置)
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jsonConvertor = new MappingJackson2HttpMessageConverter(new JSONMapper());
List<MediaType> jsonMediaTypes =new ArrayList<MediaType>();
jsonMediaTypes.add(MediaType.APPLICATION_JSON);
jsonConvertor.setSupportedMediaTypes(jsonMediaTypes);
converters.add(jsonConvertor);
addDefaultHttpMessageConverters(converters);
}