fastjson2 icon indicating copy to clipboard operation
fastjson2 copied to clipboard

[BUG] Serialization to byte[] / Deserialization to class ruins field ordering

Open ender1214 opened this issue 10 months ago • 4 comments

I apologize, I can't write in Chinese.

As the title says, fastjson2 overrides and imposes what seems to be an alphabetical / lexicographical ordering of field names. It seems to also not respect if the data type of the field enforces insertion order (LinkedHashMap, LinkedHashSet).

If this an override on the part of fastjson2, is there a way to disable it? Honestly, it seems too strong an opinion for a library to make and should only be optional and be disabled by default.

ender1214 avatar Apr 16 '24 02:04 ender1214

To add to the context, using Gson and Jackson, the order is preserved. We wanted to migrate fromt these to fastjson2 due to several benefits but the imposition of field ordering breaks expected behavior of several of our services.

Thanks.

ender1214 avatar Apr 16 '24 07:04 ender1214

Can you provide such a demo?

yanxutao89 avatar Apr 16 '24 09:04 yanxutao89

You can configure JSONType#alphabetic=false through Annotation to avoid serialized output sorting. But this sorting depends on the behavior of the compiler, which is not completely certain.

    @Test
    public void test() {
        Bean bean = new Bean();
        bean.a1 = 1;
        bean.a2 = 2;
        bean.a3 = 3;
        String json = JSON.toJSONString(bean);
        System.out.println(json);
    }

    @JSONType(alphabetic = false)
    public static class Bean {
        public int a2;
        public int a1;
        public int a3;
    }

wenshao avatar Apr 16 '24 11:04 wenshao

https://oss.sonatype.org/content/repositories/snapshots/com/alibaba/fastjson2/fastjson2/2.0.50-SNAPSHOT/

Global configuration of ordering has been supported. Please help to verify with version 2.0.50-SNAPSHOT, as follows:

 @Test
    public void test() {
       JSONFactory.setDefaultWriterAlphabetic(true); // global config

        Bean bean = new Bean();
        bean.a1 = 1;
        bean.a2 = 2;
        bean.a3 = 3;
        String json = JSON.toJSONString(bean);
        System.out.println(json);
    }

    public static class Bean {
        public int a2;
        public int a1;
        public int a3;
    }

wenshao avatar Apr 16 '24 23:04 wenshao

https://github.com/alibaba/fastjson2/releases/tag/2.0.50 2.0.50 has been released, please use the new version

wenshao avatar May 12 '24 05:05 wenshao

@wenshao 我的环境,这个设置不起作用,无效。输出的json字段还是排过序的,和model里定义的字段顺序不一样。 JSONFactory.setDefaultWriterAlphabetic(false); // global config 和 @JSONType(alphabetic = false) 这个都不起作用

hks2002 avatar Sep 14 '24 17:09 hks2002

默认排序这个设置,个人觉得不好,使得和其他库不兼容,想迁移过来就会发生问题。

hks2002 avatar Sep 14 '24 17:09 hks2002