json mapper 时间 日期 格式

单独配置的方法
Jackson格式化日期一般都是这个例子
public class CustomDateSerializer extends JsonSerializer<Date> {  
  
        @Override  
        public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {  
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
                String formattedDate = formatter.format(value);  
                jgen.writeString(formattedDate);  
        }  
}

@JsonSerialize(using = CustomDateSerializer.class)  
public Date getCreateAt() {  
        return createAt;  
}


registerModule的方式注册自定义的module
ObjectMapper mapper = super.createObjectMapper();
		UTCDateDeserializer utcDateDeserializer = new UTCDateDeserializer();
		SimpleModule newModule = new SimpleModule("UTCDateDeserializer", PackageVersion.VERSION);
		newModule.addDeserializer(Date.class, utcDateDeserializer);
		mapper.registerModule(newModule);

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.xxx.ReflectUtils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.DateDeserializers.DateDeserializer;

public class UTCDateDeserializer extends DateDeserializer {
	private Logger logger = Logger.getLogger(getClass());
	private static final long	serialVersionUID	= -6218693745160760598L;

	@Override
	protected Date _parseDate(JsonParser jp, DeserializationContext ctxt)
			throws IOException, JsonProcessingException {
		Date _parseDate = null;
		try {
			_parseDate = super._parseDate(jp, ctxt);
		} catch (Exception ex) {
			logger.trace(ex.getMessage(), ex.getCause());
			String dateStr = jp.getText().trim();
			
			DateFormat sourceDf = ctxt.getConfig().getDateFormat();
			
			if (sourceDf != null && sourceDf instanceof SimpleDateFormat) {
				String pattern = (String) ReflectUtils.getFieldValue(sourceDf, "pattern");
				DateTime dt = DateTimeFormat.forPattern(pattern).parseDateTime(dateStr);
				_parseDate = dt.toDate();
			}
		}
		return _parseDate;
	}

}

你可能感兴趣的:(mapper)