項目中用到了 @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; }
還有這個:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.33</version> </dependency>
參考文章: https://segmentfault.com/a/1190000011213222
2018/6/3: 補充一下
因為所有對象共有一個class對象,所以在將詳情字段設為可見后,再查看列表,詳情也是可見的。 最終的處理結果就是再建一個一樣的類,但詳情字段沒有@JsonIgnore. 比如AnotherDetail
也就是說,不能用上面說的修改注解來解決這個問題。但這個技術還是有其他的應用。
public class AnotherDetail {
...
private String detail;
...
}
列表用Detail, 這樣列表就沒有詳情字段。
在需要詳情的地方用AnotherDetail, 然后將Detail一個個賦給AnotherDetail.
Detail detail = db.getDetail(...); // JsonIgnore只是控制返給前端的json, 從數據庫取出時,detail字段是有值的。
AnotherDetail ad = new AnotherDetail();
...
ad.setDetail(detail.getDetail());
然后將ad返給需要的函數。