从对象中序列化指定字段的json串

       在我们写接口的时候,常常遇到我们写的实体很多字段前端都用不到。所以我们为了接口整洁。只需返回实体中部分字段即可。所以我们从对象中序列化制定字段的json串尤为重要。

1.引入maven包





com.alibaba

fastjson

1.1.40

2.json工具类

package com.qianbao.pos.mqListener;

import com.alibaba.fastjson.serializer.AfterFilter;
import com.alibaba.fastjson.serializer.BeforeFilter;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.NameFilter;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.PropertyPreFilter;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.alibaba.fastjson.serializer.ValueFilter;

public class JsonUtils {
	
	/**
     * 从对象中序列化指定字段的json串
     * @param object
     * @param keys 需要序列化的key值 目的是排除不需要vo展示的字段
     * @return
     */
    public static String object2Json(Object object, String... keys) {
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(object.getClass(),keys);
        return toJSONString(object,filter, SerializerFeature.WriteMapNullValue);
    }
	
	public static final String toJSONString(Object object, SerializeFilter filter, SerializerFeature... features) {
        SerializeWriter out = new SerializeWriter();

        try {
            JSONSerializer serializer = new JSONSerializer(out);
            for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
                serializer.config(feature, true);
            }

            serializer.config(SerializerFeature.WriteDateUseDateFormat, true);

            setFilter(serializer, filter);

            serializer.write(object);

            return out.toString();
        } finally {
            out.close();
        }
    }
	
	private static void setFilter(JSONSerializer serializer, SerializeFilter filter) {
        if (filter == null) {
            return;
        }
        
        if (filter instanceof PropertyPreFilter) {
            serializer.getPropertyPreFilters().add((PropertyPreFilter) filter);
        }

        if (filter instanceof NameFilter) {
            serializer.getNameFilters().add((NameFilter) filter);
        }

        if (filter instanceof ValueFilter) {
            serializer.getValueFilters().add((ValueFilter) filter);
        }

        if (filter instanceof PropertyFilter) {
            serializer.getPropertyFilters().add((PropertyFilter) filter);
        }

        if (filter instanceof BeforeFilter) {
            serializer.getBeforeFilters().add((BeforeFilter) filter);
        }

        if (filter instanceof AfterFilter) {
            serializer.getAfterFilters().add((AfterFilter) filter);
        }
    }

}

3.调用方式

String jsonMerchantInfo= BaseUtils.object2Json(voMerchantActInfoExcel,"payMerchantNo","channelMerchantNo","signboardName","respMsg");

你可能感兴趣的:(工具类,实体序列化部分字段,序列化实体部分字段)