Skip to content
This repository has been archived by the owner on Oct 23, 2024. It is now read-only.

Commit

Permalink
TypeUtils.cast support java.sql.Time. for issue #1644
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Dec 16, 2017
1 parent 25ce5bc commit b273b03
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/main/java/com/alibaba/fastjson/util/TypeUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -707,6 +748,9 @@ public static <T> T cast(Object obj, Class<T> 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);
}
Expand Down
16 changes: 16 additions & 0 deletions src/test/java/com/alibaba/json/bvt/issue_1600/Issue1644.java
Original file line number Diff line number Diff line change
@@ -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());
}
}

0 comments on commit b273b03

Please sign in to comment.