Skip to content

[BUG]@JSONType(serializeFeatures = JSONWriter.Feature.WriteNonStringValueAsString)对于List<Long> 类型的属性序列化时不生效 #2431

Closed
@Bruce-Lin318

Description

问题描述

@jsontype(serializeFeatures = JSONWriter.Feature.WriteNonStringValueAsString)对于List 类型的属性序列化时不生效
对于非字符串类型的数据可以正常序列化为字符串,但是List类型解析后,数组内仍为数字类型。
如果不适用@jsontype,而是使用JSON.toJSONString(obj, JSONWriter.Feature.WriteNonStringValueAsString)则无此问题

环境信息

  • OS信息: Win11
  • JDK信息:jdk 17.0.8.7.1
  • 版本信息:Fastjson2 2.0.41

重现步骤

  1. 实体类上增加@jsontype(serializeFeatures = JSONWriter.Feature.WriteNonStringValueAsString)

  2. 接口给前端返参时,Long id 的属性可以按照预期展示为字符类型,List ids 序列化后,数组内仍为数字类型

    @Data
    @JSONType(serializeFeatures = JSONWriter.Feature.WriteNonStringValueAsString)
    public static class TestClass {
        private Long id;

        private List<Long> ids;
    }

    @Test
    public void testJson() {
        TestClass testClass = new TestClass();
        testClass.setId(1L);
        testClass.setIds(List.of(1L, 2L));
        System.out.println(JSON.toJSONString(testClass));
    }

期待的正确结果

期待的正确结果为:

{"id":"1","ids":["1","2"]}

现在的结果为:

{"id":"1","ids":[1,2]}

附加信息

如果不适用@jsontype, 序列化时指定JSONWriter.Feature.WriteNonStringValueAsString,可以实现预期效果,所以猜测是对于List类型解析时注解未生效(@JSONField与@jsontype均测试过,效果相同)

    @Data
    public static class TestClass {
        private Long id;

        private List<Long> ids;
    }

    @Test
    public void testJson() {
        TestClass testClass = new TestClass();
        testClass.setId(1L);
        testClass.setIds(List.of(1L, 2L));
        System.out.println(JSON.toJSONString(testClass, JSONWriter.Feature.WriteNonStringValueAsString));
    }

打印结果:

{"id":"1","ids":["1","2"]}

Metadata

Assignees

Labels

bugSomething isn't workingfixed

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions