JackSonは値nullのフィールドを返します。
3185 ワード
正直に言うと、この問題は本当に頭が痛いです。最終的には投機的な方法を考えます。次は私の話を聞いてください。
背景
モバイルチームは、トラフィックを節約するために、アーキテクチャグループは、いくつかの値が
解決方法案1:まず思いついたのはクラスに 案2:
テスト結果
これからコードを書く時は本当にclassを使って、HashMapのような手動でつなぎ合わせる行為をできるだけ避けるべきです。本当に頭が痛いです。
背景
モバイルチームは、トラフィックを節約するために、アーキテクチャグループは、いくつかの値が
null
または""
のフィールドをフィルタリングしてしまう。null
または""
のフィールドをどのようにフィルタリングするかという方法は以下の通りである。application-local.yml
には、次のようなグローバル構成が追加されている。 jackson:
default-property-inclusion: non_null
人のこの要求も合理的ですが、webチームによっては、いくつかのデータが示されているかどうかのロジックは、APIがこのフィールドに戻ってくるかどうかによって制御されています。フィールドに戻らないと表示されないので、問題が発生します。解決方法
@JsonInclude
を加えることですが、この注釈は私の問題を解決することができません。いくつかのコードが使用されていないため、null
または""
の値のフィールドは、下のようにフィルタされます。@JsonInclude
この注釈はMap,Listのようなデータ構造には役に立たない。 HashMap map = new HashMap<>();
map.put("totalWeight", order.getTotalWeight());
map.put("source", orderSoldTo.getFromRefType());
map.put("shipToPhone", orderSoldTo.getShipToPhone());
map.put("dropShip", order.getDropShip());
map.put("queued", order.getIssueDate());
map.put("creditRelDate", order.getCreditRelDate());
JasonIncludeHashMap
を手書きで書き、考えは主にput,get,containsKey
の書き換え方法であり、@JsonInclude(value = JsonInclude.Include.CUSTOM)
に関連して注釈し、Filterを定義する。@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = JsonIncldeValueFilter.class, contentFilter = JsonIncldeValueFilter.class)
public class JasonIncludeHashMap {
private HashMap jasonIncludeHashMap=new HashMap();
public void put(String key,Object value){
jasonIncludeHashMap.put(key,value);
}
private boolean containsKey(String key){
return jasonIncludeHashMap.containsKey(key);
}
private Object get(String key){
return containsKey(key) ? jasonIncludeHashMap.get(key) : Integer.MIN_VALUE;
}
public Object getTotalWeight(){
return get("totalWeight");
}
public Object getSource(){
return get("source");
}
public Object getShipToPhone(){
return get("shipToPhone");
}
public Object getDropShip(){
return get("dropShip");
}
public Object getQueued(){
return get("queued");
}
public Object getSalesReleased(){
return get("salesReleased");
}
}
class JsonIncldeValueFilter{
@Override
public boolean equals(Object obj) {
return (obj instanceof Integer) && ((Integer) obj == Integer.MIN_VALUE);
}
}
HashMap
をJasonIncludeHashMap
に置き換えると、null
または""
の値になると、フィールドはフィルタされずに正常に戻ることができる。テスト結果
"jasonIncludeHashMap": {
"totalWeight": 0,
"source": "",
"shipToPhone": 0,
"dropShip": null,
"queued": " ",
"creditRelDate": null
}
突っ込みを入れるこれからコードを書く時は本当にclassを使って、HashMapのような手動でつなぎ合わせる行為をできるだけ避けるべきです。本当に頭が痛いです。