Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] 定制序列化,属性值如果是子类会失效 #2286

Closed
tqang opened this issue Mar 4, 2024 · 2 comments
Closed

[BUG] 定制序列化,属性值如果是子类会失效 #2286

tqang opened this issue Mar 4, 2024 · 2 comments
Labels
bug Something isn't working fixed
Milestone

Comments

@tqang
Copy link

tqang commented Mar 4, 2024

问题描述

定制序列化和反序列化,属性值如果是子类会失效,在fastjson1中是可以正常执行。
问题原因:com.alibaba.fastjson2.writer.FieldWriterObject.getObjectWriter在获取ObjectWriter时进行类型判断如果类型不一致会使用默认ObjectWriter,并没有判断该类是否是子类。

环境信息

  • OS信息: Windows11
  • JDK信息: Openjdk 1.8.0_312
  • 版本信息:2.0.47

重现步骤

public class FastJson2Test {

    public static class DateToLongSerializer implements ObjectWriter<Object> {

        @Override
        public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
            if (object == null) {
                jsonWriter.writeNull();
            } else {
                jsonWriter.writeInt64(((Date) object).getTime());
            }
        }
    }

    @Data
    public static class TestDTO {

        @JSONField(serializeUsing = DateToLongSerializer.class)
        private Date originalDate;

        @JSONField(serializeUsing = DateToLongSerializer.class)
        private Date customDate;
    }

    public static void main(String[] args) {
        TestDTO testDTO = new TestDTO();
        // 原始类型:Date
        testDTO.setOriginalDate(new Date());
        // 子类:DateTime extends Date
        testDTO.setCustomDate(DateUtil.parseDateTime("2024-03-04 10:00:00"));
        // 序列化
        String jsonString = JSON.toJSONString(testDTO);
        // 输出:{"customDate":"2024-03-04 10:00:00","originalDate":1709546199184}
    }
}

image

@tqang tqang added the bug Something isn't working label Mar 4, 2024
@wenshao
Copy link
Member

wenshao commented Mar 17, 2024

https://oss.sonatype.org/content/repositories/snapshots/com/alibaba/fastjson2/fastjson2/2.0.48-SNAPSHOT/
问题已修复,请帮忙用2.0.48-SNAPSHOT版本帮忙验证,2.0.48版本预计在3月底前发布。

@wenshao wenshao added the fixed label Mar 17, 2024
@wenshao wenshao added this to the 2.0.48 milestone Mar 17, 2024
@wenshao
Copy link
Member

wenshao commented Mar 25, 2024

@wenshao wenshao closed this as completed Mar 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working fixed
Projects
None yet
Development

No branches or pull requests

2 participants