diff --git a/src/main/java/com/alibaba/fastjson/util/TypeUtils.java b/src/main/java/com/alibaba/fastjson/util/TypeUtils.java index 52368b22df..4b30e74810 100755 --- a/src/main/java/com/alibaba/fastjson/util/TypeUtils.java +++ b/src/main/java/com/alibaba/fastjson/util/TypeUtils.java @@ -415,6 +415,47 @@ public static java.sql.Date castToSqlDate(Object value){ return new java.sql.Date(longValue); } + public static java.sql.Time castToSqlTime(Object value){ + if(value == null){ + return null; + } + if(value instanceof java.sql.Time){ + return (java.sql.Time) value; + } + if(value instanceof java.util.Date){ + return new java.sql.Time(((java.util.Date) value).getTime()); + } + if(value instanceof Calendar){ + return new java.sql.Time(((Calendar) value).getTimeInMillis()); + } + long longValue = 0; + if(value instanceof Number){ + longValue = ((Number) value).longValue(); + } + if(value instanceof String){ + String strVal = (String) value; + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + if(isNumber(strVal)){ + longValue = Long.parseLong(strVal); + } else{ + JSONScanner scanner = new JSONScanner(strVal); + if(scanner.scanISO8601DateIfMatch(false)){ + longValue = scanner.getCalendar().getTime().getTime(); + } else{ + throw new JSONException("can not cast to Timestamp, value : " + strVal); + } + } + } + if(longValue <= 0){ + throw new JSONException("can not cast to Date, value : " + value); // TODO 忽略 1970-01-01 之前的时间处理? + } + return new java.sql.Time(longValue); + } + public static java.sql.Timestamp castToTimestamp(Object value){ if(value == null){ return null; @@ -707,6 +748,9 @@ public static T cast(Object obj, Class clazz, ParserConfig config){ if(clazz == java.sql.Date.class){ return (T) castToSqlDate(obj); } + if(clazz == java.sql.Time.class){ + return (T) castToSqlTime(obj); + } if(clazz == java.sql.Timestamp.class){ return (T) castToTimestamp(obj); } diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1644.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1644.java new file mode 100644 index 0000000000..caa9319bd6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1644.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.sql.Time; + +public class Issue1644 extends TestCase { + public void test_for_issue() throws Exception { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("time", 1324138987429L); + + Time time = jsonObject.getObject("time", java.sql.Time.class); + assertEquals(1324138987429L, time.getTime()); + } +}