zoukankan      html  css  js  c++  java
  • 通过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对应的值被判为空,故最后不加入序列化。

  • 相关阅读:
    mysql 常用命令
    mysql 存储过程知识点
    position 属性值:relative 与 absolute 区别
    spring 注解列表
    spring aop 术语
    socket、WebSocket
    spring mvc 基础
    requestAnimationFrame 提高动画性能的原因
    markdown 知识点
    SpringMVC Controller 介绍及常用注解
  • 原文地址:https://www.cnblogs.com/kincolle/p/7246365.html
Copyright © 2011-2022 走看看