PageRenderTime 360ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/com/alibaba/fastjson/parser/deserializer/SqlDateDeserializer.java

https://bitbucket.org/xiejuntao/xdesktop
Java | 61 lines | 48 code | 12 blank | 1 comment | 12 complexity | 717323632c0035698ef52d8e1a575c22 MD5 | raw file
  1. package com.alibaba.fastjson.parser.deserializer;
  2. import java.lang.reflect.Type;
  3. import java.text.DateFormat;
  4. import java.text.ParseException;
  5. import java.util.Date;
  6. import com.alibaba.fastjson.JSONException;
  7. import com.alibaba.fastjson.parser.DefaultJSONParser;
  8. import com.alibaba.fastjson.parser.JSONScanner;
  9. import com.alibaba.fastjson.parser.JSONToken;
  10. public class SqlDateDeserializer extends AbstractDateDeserializer implements ObjectDeserializer {
  11. public final static SqlDateDeserializer instance = new SqlDateDeserializer();
  12. @SuppressWarnings("unchecked")
  13. protected <T> T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object val) {
  14. if (val == null) {
  15. return null;
  16. }
  17. if (val instanceof java.util.Date) {
  18. val = new java.sql.Date(((Date) val).getTime());
  19. } else if (val instanceof Number) {
  20. val = (T) new java.sql.Date(((Number) val).longValue());
  21. } else if (val instanceof String) {
  22. String strVal = (String) val;
  23. if (strVal.length() == 0) {
  24. return null;
  25. }
  26. long longVal;
  27. JSONScanner dateLexer = new JSONScanner(strVal);
  28. if (dateLexer.scanISO8601DateIfMatch()) {
  29. longVal = dateLexer.getCalendar().getTimeInMillis();
  30. } else {
  31. DateFormat dateFormat = parser.getDateFormat();
  32. try {
  33. java.util.Date date = (java.util.Date) dateFormat.parse(strVal);
  34. return (T) new java.sql.Date(date.getTime());
  35. } catch (ParseException e) {
  36. // skip
  37. }
  38. longVal = Long.parseLong(strVal);
  39. }
  40. return (T) new java.sql.Date(longVal);
  41. } else {
  42. throw new JSONException("parse error : " + val);
  43. }
  44. return (T) val;
  45. }
  46. public int getFastMatchToken() {
  47. return JSONToken.LITERAL_INT;
  48. }
  49. }