Skip to content

Commit abc326c

Browse files
committed
improved for java.sql.Time support, for issue alibaba#2156
1 parent 64ec3ef commit abc326c

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/main/java/com/alibaba/fastjson/serializer/DateCodec.java

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ public void write(JSONSerializer serializer, Object object, Object fieldName, Ty
5050
return;
5151
}
5252

53-
if (object.getClass() == java.sql.Date.class) {
53+
Class<?> clazz = object.getClass();
54+
if (clazz == java.sql.Date.class) {
5455
long millis = ((java.sql.Date) object).getTime();
5556
TimeZone timeZone = serializer.timeZone;
5657
int offset = timeZone.getOffset(millis);
@@ -59,6 +60,14 @@ public void write(JSONSerializer serializer, Object object, Object fieldName, Ty
5960
return;
6061
}
6162
}
63+
64+
if (clazz == java.sql.Time.class) {
65+
long millis = ((java.sql.Time) object).getTime();
66+
if (millis < 24L * 60L * 60L * 1000L) {
67+
out.writeString(object.toString());
68+
return;
69+
}
70+
}
6271

6372
Date date;
6473
if (object instanceof Date) {
@@ -79,15 +88,15 @@ public void write(JSONSerializer serializer, Object object, Object fieldName, Ty
7988
}
8089

8190
if (out.isEnabled(SerializerFeature.WriteClassName)) {
82-
if (object.getClass() != fieldType) {
83-
if (object.getClass() == java.util.Date.class) {
91+
if (clazz != fieldType) {
92+
if (clazz == java.util.Date.class) {
8493
out.write("new Date(");
8594
out.writeLong(((Date) object).getTime());
8695
out.write(')');
8796
} else {
8897
out.write('{');
8998
out.writeFieldName(JSON.DEFAULT_TYPE_KEY);
90-
serializer.write(object.getClass().getName());
99+
serializer.write(clazz.getName());
91100
out.writeFieldValue(',', "val", ((Date) object).getTime());
92101
out.write('}');
93102
}

src/test/java/com/alibaba/json/bvt/issue_2100/Issue2156.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,10 @@ public void test_for_issue() throws Exception {
99
String str = JSON.toJSONStringWithDateFormat(date, JSON.DEFFAULT_DATE_FORMAT);
1010
assertEquals("\"2018-07-15\"", str);
1111
}
12+
13+
public void test_for_issue_time() throws Exception {
14+
java.sql.Time date = java.sql.Time.valueOf("12:13:14");
15+
String str = JSON.toJSONStringWithDateFormat(date, JSON.DEFFAULT_DATE_FORMAT);
16+
assertEquals("\"12:13:14\"", str);
17+
}
1218
}

0 commit comments

Comments
 (0)