FastJson bean序列化属性顺序问题

fastjson序列化一个java bean,默认是根据fieldName的字母序进行序列化的,你可以通过ordinal指定字段的顺序,这个特性需要1.1.42以上版本。示例如下。

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField; /**
* Created by gary on 16/6/21.
*/
public class FieldSequence { @JSONField(ordinal=1,name = "name_1")
private String name;
@JSONField(ordinal=2)
private int age;
@JSONField(ordinal=3)
private String gender; public FieldSequence(String name,int age,String gender){ this.name = name;
this.age = age;
this.gender = gender;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getGender() {
return gender;
} public void setGender(String gender) {
this.gender = gender;
} public static void main(String[] args){ FieldSequence fieldSequence = new FieldSequence("lily",20,"woman");
System.out.println(JSON.toJSONString(fieldSequence));
} }

属性中不使用@JSONField注解输出如下

{"age":20,"gender":"woman","name":"lily"}  //按属性字母顺序排序

使用注解后,上面程序输出如下

{"name_1":"lily","age":20,"gender":"woman"}

@JSONField注解中可以设置属性顺序,重新设置属性名称,格式等,SerializerFeature(这是个枚举类,里面封装的有很多序列化的格式需求)

上一篇:应该怎么理解 app = Flask(__name__)


下一篇:hdu 确定比赛名次(拓扑排序)