通过fastjson将一个对象序列化为json,同时加入指定的序列化逻辑

主函数:

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对应的值被判为空,故最后不加入序列化。

posted @ 2017-07-27 18:05  kincolle  阅读(1366)  评论(0编辑  收藏  举报