指定JSON.toJSONString中实体类属性的输出顺序

JSON.toJSONString过程中出现实体类的属性与转换之前的顺序不一致
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));
    }
使用注解指定属性的输出顺序


第一种:通过在实体类添加@JSONType(orders={"name","age","gender","height","weight"})
@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;
}
第二种:在属性上添加@JSONField(ordinal = 1)
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;
}

指定JSON.toJSONString中实体类属性的输出顺序

上一篇:用HTML在叙述视图开发性能平铺视图


下一篇:js替换字符串中所有斜杠