ITeye博客

自定义ObjectMapper

conkeyn · 2015-03-02 16:57 · Java · Java/Spring、Spring MVC · 编程语言 · Markdown

d

 

import java.io.IOException;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer;

/**
 * 支持多种日期格式的解析
 */
@SuppressWarnings("deprecation")
class CustomDateDeseralizer extends UntypedObjectDeserializer {

  Logger logger = LoggerFactory.getLogger(getClass());

  private static final long serialVersionUID = -2275951539867772400L;

  @Override
  public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {

    if (jp.getCurrentTokenId() == JsonTokenId.ID_STRING) {
      try {
        return DateUtils.parseDate(jp.getText(),
            new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "MM/dd/yyyy",
                "yyyy.MM.dd G 'at' HH:mm:ss z", "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
                "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz"});
      } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return super.deserialize(jp, ctxt);
      }
    } else {
      return super.deserialize(jp, ctxt);
    }
  }
}

 

import java.text.SimpleDateFormat;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;

/**
 * json与java对象之间转化器
 * 
 * @version 1.0.0
 * @since 2014年10月21日 下午3:11:39
 */
public final class JsonObjectMapper extends ObjectMapper {
  /** */
  private static final long serialVersionUID = 4563671462132723274L;

  public JsonObjectMapper() {
    super();
    // 从JSON到java object
    // 没有匹配的属性名称时不作失败处理
    this.configure(MapperFeature.AUTO_DETECT_FIELDS, true);

    // 反序列化
    // 禁止遇到空原始类型时抛出异常,用默认值代替。
    this.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    this.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
    // 禁止遇到未知(新)属性时报错,支持兼容扩展
    this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    this.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    this.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    // 按时间戳格式读取日期
    // this.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, true);
    this.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
    this.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
    this.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    // 序列化
    // 禁止序列化空值
    this.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    this.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
    this.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true);
    // 按时间戳格式生成日期
    // this.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, true);
    this.configure(SerializationFeature.FLUSH_AFTER_WRITE_VALUE, true);
    this.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, true);
    // 不包含空值属性
    this.setSerializationInclusion(Include.NON_EMPTY);
    this.setSerializationInclusion(Include.NON_NULL);
    // this.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
    // 是否缩放排列输出,默认false,有些场合为了便于排版阅读则需要对输出做缩放排列
    this.configure(SerializationFeature.INDENT_OUTPUT, false);
    // 设置全局的时间转化
    SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    this.setDateFormat(smt);
    // 设置日期反序列化组件
    SimpleModule dateDeserializerModule = new SimpleModule();
    dateDeserializerModule.addDeserializer(Object.class, new CustomDateDeseralizer());
    this.registerModule(dateDeserializerModule);
    // 注意:不要开启序列化和反序列化时为对象附加@class属性(坑)
    // this.enableDefaultTyping(ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT, As.PROPERTY);
  }

}

 

/**
 * 测试objectMapper特性
 * 
 * @version 1.0.0
 * @since 2015年3月2日 下午2:02:05
 * @param <T> 泛型参数
 */
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
//只包含非空属性
@JsonInclude(Include.NON_NULL)
@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY)
public class Msg<T>
{
	
	@JsonProperty(required = false, value = "code")
	private String code;

	/** 消息内容 */
	@JsonProperty(required = false, value = "msg")
	private String msg;
	
	@JsonProperty(required = false, value = "name")
	String name;
	
	@JsonProperty(required = false, value = "payload")
	@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY)
	T payload;

	public T getPayload()
	{
		return payload;
	}

	public void setPayload(T payload)
	{
		this.payload = payload;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public String getCode()
	{
		return code;
	}

	public void setCode(String code)
	{
		this.code = code;
	}

	public String getMsg()
	{
		return msg;
	}

	public void setMsg(String msg)
	{
		this.msg = msg;
	}
}

 

/**
 * 测试objectMapper特性
 * 
 * @version 1.0.0
 * @since 2015年3月2日 下午2:02:05
 * @param <T> d
 */
@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY)
public class TypeMap<T>
{
	@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY)
	//指示Map的value是使用@JsonTypeInfo进行解析
	Map<String, T> map = new HashMap<String, T>();

	public Map<String, T> getMap()
	{
		return map;
	}

	public void setMap(Map<String, T> map)
	{
		this.map = map;
	}

}

 

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;

/**
 * 测试类
 * 
 * @version 1.0.0
 * @since 2015年2月5日 上午10:32:38
 */
@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY)
public class User implements Serializable
{

	private String id;
	private String name;

	private int age;

	public String getId()
	{
		return id;
	}

	public void setId(String id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public int getAge()
	{
		return age;
	}

	public void setAge(int age)
	{
		this.age = age;
	}
}

 

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;

/**
 * 测试类
 * 
 * @version 1.0.0
 * @since 2015年2月5日 上午10:32:38
 */
@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY)
public class User1 implements Serializable
{

	/** */
	private static final long serialVersionUID = 5723985672168696454L;
	private String id;
	private String name;

	private int age;

	public String getId()
	{
		return id;
	}

	public void setId(String id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public int getAge()
	{
		return age;
	}

	public void setAge(int age)
	{
		this.age = age;
	}
}

 

 

d

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。