FastJson bean序列化屬性順序問題
阿新 • • 發佈:2018-11-08
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(這是個列舉類,裡面封裝的有很多序列化的格式需求)