通過fastjson將一個對象序列化為json,同時加入指定的序列化邏輯

來源:互聯網
上載者:User

標籤:.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,同時加入指定的序列化邏輯

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.