我已经解决了扩展ResponseEntity这样的问题:
public class ResponseViewEntity<T> extends ResponseEntity<ContainerViewEntity<T>> { private Class<? extends baseView> view; public ResponseViewEntity(HttpStatus statusCode) { super(statusCode); } public ResponseViewEntity(T body, HttpStatus statusCode) { super(new ContainerViewEntity<T>(body, baseView.class), statusCode); } public ResponseViewEntity(T body, Class<? extends baseView> view, HttpStatus statusCode) { super(new ContainerViewEntity<T>(body, view), statusCode); }}和ContainerViewEntity封装对象和选定的视图
public class ContainerViewEntity<T> { private final T object; private final Class<? extends baseView> view; public ContainerViewEntity(T object, Class<? extends baseView> view) { this.object = object; this.view = view; } public T getObject() { return object; } public Class<? extends baseView> getView() { return view; } public boolean hasView() { return this.getView() != null; }}之后,我们仅转换具有良好视图的对象。
public class JsonViewMessageConverter extends MappingJackson2HttpMessageConverter { @Override protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (object instanceof ContainerViewEntity && ((ContainerViewEntity) object).hasView()) { writeView((ContainerViewEntity) object, outputMessage); } else { super.writeInternal(object, outputMessage); } } protected void writeView(ContainerViewEntity view, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { JsonEncoding encoding = this.getJsonEncoding(outputMessage.getHeaders().getContentType()); ObjectWriter writer = this.getWriterForView(view.getView()); JsonGenerator jsonGenerator = writer.getFactory().createGenerator(outputMessage.getBody(), encoding); try { writer.writevalue(jsonGenerator, view.getObject()); } catch (IOException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } } private ObjectWriter getWriterForView(Class<?> view) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); return mapper.writer().withView(view); }}最后,我启用转换器
<mvc:annotation-driven> <mvc:message-converters> <bean /> </mvc:message-converters></mvc:annotation-driven>
就是这样,我可以在控制器中选择“视图”
@Override@RequestMapping(value = "/get_by_id/{accountId}", method = RequestMethod.GET, headers = "Accept=application/json")public ResponseViewEntity<Account> getById(@PathVariable(value = "accountId") Long accountId) throws ServiceException { return new ResponseViewEntity<Account>(this.getAccountSrv().getById(accountId), PublicView.class, HttpStatus.OK);}


