项目中用到了 @JsonIgnore 注解,因为类中有个详细信息, 这个详细信息在返给前端列表时用不到,只在查看详情时才会用到。所以详情字段加上了@JsonIgnore,它的默认值是true.
所以在查看详情时,还要给前端返回这个详情字段。就要动态将@JsonIgnore设置成false。这个是通过反射完成的。
因为查看详情通常情况下,只返回一个pojo,所以在这里用反射,不会影响系统的性能。
假设 一个类, Detail
public class Detail implements Serializable { ... @JsonIgnore private String detail; ... }
现在要将@JsonIgnore的值改为false
public Detail getDetail(String id) { Detail detail = repository.findOne(id); try { Field detailField = message.getClass().getDeclaredField("detail"); if (detailField != null) { detailField.setAccessible(true); JsonIgnore annotation = detailField.getAnnotation(JsonIgnore.class); if (annotation != null) { InvocationHandler ih = Proxy.getInvocationHandler(annotation); Field memberValuesField = ih.getClass().getDeclaredField("memberValues"); memberValuesField.setAccessible(true); Map memberValues = (Map)memberValuesField.get(ih); memberValues.put("value", false); // set value to false } } }catch(Exception e) { e.printStackTrace(); } return Detail; }
参考文章: https://segmentfault.com/a/1190000011213222