java - fastjson toJSONString() 属性排序
黄舟
黄舟 2017-04-17 17:42:15
0
1
559

最近使用fastjson序列化对象时,发现输出的json字符串中是按属性进行了排序。

public class Person {
    private String name;
    private Integer age;
    private String gender;
    private Double height;
    private Double weight;
    //省略get,set方法
}
public class FastJsonTest {

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Tom");
        person.setAge(20);
        person.setGender("Male");
        person.setHeight(180.5);
        person.setWeight(80.5);
        
        System.out.println(JSON.toJSONString(person));
    }
}

输出:

{"age":20,"gender":"Male","height":180.5,"name":"Tom","weight":80.5}

通过@JSONType,@JSONField注解可以定义属性的顺序

@JSONType(orders={"name","age","gender","height","weight"})
public class Person {
    private String name;
    private Integer age;
    private String gender;
    private Double height;
    private Double weight;
}

或者

public class Person {
    @JSONField(ordinal = 1)
    private String name;
    @JSONField(ordinal = 2)
    private Integer age;
    @JSONField(ordinal = 3)
    private String gender;
    @JSONField(ordinal = 4)
    private Double height;
    @JSONField(ordinal = 5)
    private Double weight;
}

输出:

{"name":"Tom","age":20,"gender":"Male","height":180.5,"weight":80.5}


如果每个VO都显示的指定顺序会比较繁琐。所以,我的问题是:
1、fastjson设计为按顺序输出的目的是什么?

2、有没有全局的配置,来取消属性排序的功能?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
阿神

FastJson after version 1.2.3 does not have this problem

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!