標籤:.json static value override port alibaba check logs 一個
主函數:
import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.serializer.ValueFilter;import com.google.common.base.Preconditions;public class xiaomi { public static void main(String[] args) { A a = new A(); String json =ok.object2Json(a); System.out.println(json); }}
實體類:
class A{ int a; int b=1; String des ="wuhan"; String dep ="xiantao"; public String getDes() { return des; } public void setDes(String des) { this.des = des; } public String getDep() { return dep; } public void setDep(String dep) { this.dep = dep; } public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; }}
實體類
序列化類別:
class ok{ public static String object2Json(Object o){ Preconditions.checkNotNull(o); String json = JSON.toJSONString(o, new ValueFilter() { @Override public Object process(Object object, String name, Object value) { if (name == "a" && value.equals(0))//當有屬性a的至等於0時,json的值賦為null return null; else if (name == "d" && value == null)//當有屬性d的至等於null時,json的值賦為"",此處因為實體類A裡沒有名字為d的屬性,故實際不會被執行 return ""; return value; } }); return json; }}
運行結果:
{"b":1,"dep":"xiantao","des":"wuhan"}
Process finished with exit code 0
總結:類a的屬性a,因為值等於零,最後json對應的值被判為空白,故最後不加入序列化。
通過fastjson將一個對象序列化為json,同時加入指定的序列化邏輯