小技巧集锦

  1. jackson JsonDeserialize 使用方法:
    1. 实现方法
    2. 注解写在set方法上。
    3. public class CustomJsonDateDeserializer extends JsonDeserializer<Date> {
      	private SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
      
      	@Override
      	public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
      		String text = jp.getText();
      
      		if (StringUtils.hasText(text)) {
      			try {
      				if (text.indexOf(":") == -1 && text.length() == 10) {
      					return this.dateFormat.parse(text);
      				} else if (text.indexOf(":") > 0 && text.length() == 19) {
      					return this.datetimeFormat.parse(text);
      				} else {
      					throw new IllegalArgumentException("Could not parse date, date format is error ");
      				}
      			} catch (ParseException ex) {
      				IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + ex.getMessage());
      				iae.initCause(ex);
      				throw iae;
      			}
      		} else {
      			return null;
      		}
      	}
      
      }

猜你喜欢

转载自my.oschina.net/u/2319418/blog/1833305