From 5ca2b3bd42add17fe2c4ff56d88ea5cfd457ae30 Mon Sep 17 00:00:00 2001 From: fanzhongwei Date: Tue, 29 Sep 2020 14:59:55 +0800 Subject: [PATCH] fix issue https://github.com/alibaba/fastjson/issues/3473 --- .../fastjson/serializer/DateCodec.java | 2 +- .../SerializeWriterJavaSqlDateTest.java | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/alibaba/fastjson/serializer/issue3473/SerializeWriterJavaSqlDateTest.java diff --git a/src/main/java/com/alibaba/fastjson/serializer/DateCodec.java b/src/main/java/com/alibaba/fastjson/serializer/DateCodec.java index a6d63ba957..31df03ae4f 100644 --- a/src/main/java/com/alibaba/fastjson/serializer/DateCodec.java +++ b/src/main/java/com/alibaba/fastjson/serializer/DateCodec.java @@ -51,7 +51,7 @@ public void write(JSONSerializer serializer, Object object, Object fieldName, Ty } Class clazz = object.getClass(); - if (clazz == java.sql.Date.class) { + if (clazz == java.sql.Date.class && !out.isEnabled(SerializerFeature.WriteDateUseDateFormat)) { long millis = ((java.sql.Date) object).getTime(); TimeZone timeZone = serializer.timeZone; int offset = timeZone.getOffset(millis); diff --git a/src/test/java/com/alibaba/fastjson/serializer/issue3473/SerializeWriterJavaSqlDateTest.java b/src/test/java/com/alibaba/fastjson/serializer/issue3473/SerializeWriterJavaSqlDateTest.java new file mode 100644 index 0000000000..e7c8a9f948 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/serializer/issue3473/SerializeWriterJavaSqlDateTest.java @@ -0,0 +1,45 @@ +package com.alibaba.fastjson.serializer.issue3473; + +import java.sql.Date; +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.time.DateUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +/** + * package com.alibaba.fastjson.serializer.issue3473
+ * description: java.sql.Date序列化测试
+ * Copyright 2019 thunisoft, Inc. All rights reserved. + * + * @author fanzhongwei + * @date 20-9-29 + */ +public class SerializeWriterJavaSqlDateTest { + + private Map data = new HashMap(1, 1); + + @Before + public void before() throws ParseException { + data.put("sqlDate", new Date(DateUtils.parseDate("2020-09-29", "yyyy-MM-dd") + .getTime())); + } + + @Test + public void yyyy_MM_dd_HH_mm_ss_test() { + String json = JSON.toJSONString(data, SerializerFeature.WriteDateUseDateFormat); + Assert.assertEquals("{\"sqlDate\":\"2020-09-29 00:00:00\"}", json); + } + + @Test + public void yyyy_MM_dd_test() { + String json = JSON.toJSONString(data); + Assert.assertEquals("{\"sqlDate\":\"2020-09-29\"}", json); + } +}