通过情况下对前端输出json格式不需要关注字段顺序,但某些特殊场景需要设置字段输出顺序(例nginx需要对特殊字段顺序进行加密处理);框架有默认的顺序,如 jackson 默认使用字段声明的顺序, fastjson 默认是使用字典序。
使用@JsonPropertyOrder指定顺序
public class JacksonController {
public static void main(String[] args) throws JsonProcessingException {
//1: 默认顺序:字段声明的顺序
Cat1 cat1 = new Cat1();
cat1.setAge(1);
cat1.setName("咪咪");
cat1.setHobby("sleep");
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(cat1);
System.out.println("json:"+json.toString());
//2: 使用@JsonPropertyOrder指定顺序
Cat2 cat2 = new Cat2();
cat2.setAge(1);
cat2.setName("咪咪002");
cat2.setHobby("eat");
String json2 = objectMapper.writeValueAsString(cat2);
System.out.println("json2:"+json2.toString());
}
}
@Data
class Cat1 {
private String hobby;
private String name;
private Integer age;
}
@Data
@JsonPropertyOrder({"name", "age", "hobby"})
class Cat2 {
private String hobby;
private String name;
private Integer age;
}
1、使用@JsonField的ordinal指定顺序,数越小优先级越高,默认为0
2、使用@JSONType的orders属性指定字段顺序
public class FastjsonController {
public static void main(String[] args){
//1: 默认顺序:字段声明的顺序
Dog1 dog1 = new Dog1();
dog1.setAge(1);
dog1.setName("嘟嘟001");
dog1.setHobby("eat");
String json = JSON.toJSONString(dog1);
System.out.println("默认顺序(字段声明的顺序):"+json.toString());
//2: 使用@JsonField的ordinal指定顺序,数越小优先级越高,默认为0
Dog2 dog2 = new Dog2();
dog2.setAge(1);
dog2.setName("嘟嘟002");
dog2.setHobby("eat");
String json2 = JSON.toJSONString(dog2);
System.out.println("JsonField ordinal指定顺序:"+json2.toString());
//3: 使用@JSONType的orders属性指定字段顺序
Dog3 dog3 = new Dog3();
dog3.setAge(1);
dog3.setName("嘟嘟003");
dog3.setHobby("eat");
String json3 = JSON.toJSONString(dog3);
System.out.println("JSONType orders指定顺序:"+json3.toString());
}
}
@Data
class Dog1 {
private String hobby;
private String name;
private Integer age;
}
@Data
class Dog2 {
@JSONField(ordinal = 3)
private String hobby;
@JSONField(ordinal = 2)
private String name;
@JSONField(ordinal = 1)
private Integer age;
}
@Data
@JSONType(orders = {"name", "age", "hobby"})
class Dog3 {
private String hobby;
private String name;
private Integer age;
}
将json字段串转换成JSON对象时,如要保持原字段顺序,fastjson使用Feature.OrderedField参数;
JSON.parseObject(json, Feature.OrderedField);
SONObject.parseObject(json, Feature.OrderedField);