从对象中序列化指定字段的json串
在我们写接⼝的时候,常常遇到我们写的实体很多字段前端都⽤不到。所以我们为了接⼝整洁。只需返回实体中部分字段即可。所以我们从对象中序列化制定字段的json串尤为重要。
1.引⼊maven包
<!-- fastjson json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
fastjson怎么用<version>1.1.40</version>
</dependency>
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, keys) {
SimplePropertyPreFilter filter = new Class(),keys);
return toJSONString(object,filter, SerializerFeature.WriteMapNullValue);
}
public static final String toJSONString(Object object, SerializeFilter filter, features) {
SerializeWriter out = new SerializeWriter();
try {
JSONSerializer serializer = new JSONSerializer(out);
for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
}
setFilter(serializer, filter);
serializer.write(object);
String();
} finally {
out.close();
}
}
private static void setFilter(JSONSerializer serializer, SerializeFilter filter) {
if (filter == null) {
return;
}
if (filter instanceof PropertyPreFilter) {
}
if (filter instanceof NameFilter) {
}
if (filter instanceof ValueFilter) {
}
if (filter instanceof PropertyFilter) {
}
if (filter instanceof BeforeFilter) {
}
if (filter instanceof AfterFilter) {
}
}
}
3.调⽤⽅式
String jsonMerchantInfo= BaseUtils.object2Json(voMerchantActInfoExcel,"payMerchantNo","channelMerchantNo","signboardName","respMsg");
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论