JsonMapper处理兼容多种时间转换问题

        有时候由于系统问题,在使用JsonMapper进行json格式转换成实体的时候,有可能会出现时间存在多种格式的情况,而原本的JsonMapper的setformat方法设置时间格式时却只能指定一种时间格式进行转换,最后导致整个json的转换失败。

       我在学习JsonMapper的时候并没有很透彻,只是根据网上的文章配置一些简单的参数,所以一时对这种情况无耻从下手。所以我最先想到的方法是重写这个DateFormat时间转换类,可是却非常尴尬由于知识浅薄,看不懂JsonMapper源码,不知如何正确地设置JsonMapper时间转换的反序列化中。所以我从网上找到一个例子,和大家分享一下!

 

重写了DateFormat类

package yspay.manager.dsf.util;

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * .扩展jackson日期格式化支持格式
 */
public class ObjectMapperDateFormatExtend extends DateFormat {

	private static final long serialVersionUID = 1L;
	private DateFormat dateFormat;

	// 该格式为测试环境格式
	private SimpleDateFormat format1 = new SimpleDateFormat(
			"yyy-MM-dd HH:mm:ss");

	// 构造函数传入objectmapper默认的dateformat
	public ObjectMapperDateFormatExtend(DateFormat dateFormat) {
		this.dateFormat = dateFormat;
	}

	// 序列化时会执行这个方法
	@Override
	public StringBuffer format(Date date, StringBuffer toAppendTo,
			FieldPosition fieldPosition) {
		return dateFormat.format(date, toAppendTo, fieldPosition);
	}

	// 反序列化时执行此方法,我们先让他执行我们自己的format,如果异常则执行其他的
	// 当然这里只是简单实现,可以有更优雅的方式来处理更多的格式
	@Override
	public Date parse(String source, ParsePosition pos) {
		Date date = null;

		try {
			date = dateFormat.parse(source, pos);
		} catch (Exception e) {
			// 不抛出异常,置空交给下个格式进行处理
			date = null;
		}
		if (date == null) {
			try {
				date = format1.parse(source, pos);
			} catch (Exception ex) {
				date = null;
			}
		}

		return date;
	}

	// 此方法在objectmapper 默认的dateformat里边用到,这里也要重写
	@Override
	public Object clone() {
		DateFormat dateFormat = (DateFormat) this.dateFormat.clone();
		return new ObjectMapperDateFormatExtend(dateFormat);
	}
}

 

然后在ObjectMapper的参数初始化设置反序列化

public class JsonObjectMapper extends ObjectMapper {

	/**
	 * 意义,目的和功能,以及被用到的地方
*/ private static final long serialVersionUID = 1L; public JsonObjectMapper() { super(); // 设置默认时间格式 this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss")); // 反序列化扩展日期格式支持(兼容其它格式) DateFormat dateFormat = this.getDateFormat(); this.setConfig(this.getDeserializationConfig().with( new ObjectMapperDateFormatExtend(dateFormat))); } }

 

这样的话在原来设置的时间格式(yyyy-MM-dd:HH:mm:ss)基础上,兼容了(yyyy-MM-dd HH:mm:ss)时间格式。对应的,如果你有需要,你可以兼容更多的时间格式。

 

JsonObjectMapper mapper = new JsonObjectMapper();

// 由于当空字段同步到大数据库时会保存成String类型的null
List testBeanList = mapper.readValue(jsonData.toJSONString()
		, new TypeReference>() {
});

 

这样就能实现当一个json转换实体的时候,时间格式的兼容问题了。

 

————————————————————————————————

有个题外话就是:

当如果你的代码需要使用sonar进行代码质量检测的时候,就会出现一个问题:在sonar的规则里,clone()的重写是不被允许的,所以,这种方法仅供参考!同样的,希望各位大神分享更好的方法,老实说ObjectMapper源码我这个菜鸟怎得不怎么看的懂!

你可能感兴趣的:(Json)