本文主要是介绍Jackson 转json 时日期格式化,排除字段,包含字段,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package com.dj.spring3.jackson;import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.introspect.BasicBeanDescription;
import org.codehaus.jackson.map.ser.BeanSerializerFactory;
/**
* @description 重写jackson 序列化工厂
* @author liudejian
* @date 2013-03-21
*/
public class BidBeanSerializerFactory extends BeanSerializerFactory {
public final static BidBeanSerializerFactory instance = new BidBeanSerializerFactory(null);
private Object filterId;
protected BidBeanSerializerFactory(Config config) {
super(config);
}
@Override
protected Object findFilterId(SerializationConfig config,
BasicBeanDescription beanDesc) {
return getFilterId();
}
public Object getFilterId() {
return filterId;
}
public void setFilterId(Object filterId) {
this.filterId = filterId;
}
}
=======测试代码======================
package com.dj.spring3.jackson;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import com.dj.spring3.model.Fruit;
public class MyTest {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Fruit f = new Fruit();
f.setName("8888");
f.setQuality(1000);
f.setBuyTime(new Date());
ObjectMapper objectMapper = new ObjectMapper();
JsonEncoding encoding = JsonEncoding.UTF8;
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
//排除
SimpleFilterProvider fileter = new SimpleFilterProvider();
fileter.addFilter(
"executeFilter",
SimpleBeanPropertyFilter.serializeAllExcept(new String[] {
"quality" }));
objectMapper.setFilters(fileter);
//仅包含
// SimpleFilterProvider fileter2 = new SimpleFilterProvider();
// fileter2.addFilter(
// "includeFilter",
// SimpleBeanPropertyFilter.filterOutAllExcept(new String[] {
// "id", "quality" }));
// objectMapper.setFilters(fileter2);
//设置日期格式化
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
JsonGenerator generator = objectMapper.getJsonFactory()
.createJsonGenerator(System.out, encoding);
BidBeanSerializerFactory bidBeanFactory = BidBeanSerializerFactory.instance;
bidBeanFactory.setFilterId("executeFilter"); //如果是仅包含这里填写 includeFilter
objectMapper.setSerializerFactory(bidBeanFactory);
objectMapper.writeValue(generator, f);
}
}
这篇关于Jackson 转json 时日期格式化,排除字段,包含字段的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!