如何在Jackson上指定字段序列化顺序

时间:2017-04-14 09:27:35

标签: serialization jackson

我有一个名为Test的类扩展了另一个名为BasicTest的类,该类如下所示:

public class Test extends BasicTest{
    private String name;
    private Integer age;

   // ... Getter and Setter
}

public class BasicTest{
    private String code;
    private Long time;

   // ... Getter and Setter
}

我使用jersey提供RESTFul Api,这是端点的代码:

@Path("/test")
public class MyEndpoint{
     @Get
     @Produce(MediaType.APPLICATION_JSON)
     public Test myTest(){
          Test test = new Test();
          test.setName("Chris");
          test.setAge(29);
          test.setCode("200");
          test.setTime(100)
          return test;
     }
}

我期待的回应是:

{
  "name": "Chris",
  "age": 28,
  "code": "200",
  "time": 100
}

但我得到了:

{
  "code":"200",
  "time":100,
  "name":"Chris",
  "age":28
}

我的jackson对象映射器提供程序配置是:

public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
final ObjectMapper defaultObjectMapper;

public ObjectMapperProvider() {
    defaultObjectMapper = createDefaultMapper();
}

@Override
public ObjectMapper getContext(Class<?> type) {
    return defaultObjectMapper;
}

private static ObjectMapper createDefaultMapper() {
    final ObjectMapper result = new ObjectMapper();
    //enable
    result.enable(SerializationFeature.INDENT_OUTPUT);

    //disable
    result.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    result.disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
    result.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    //include
    result.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    result.configure(MapperFeature.USE_ANNOTATIONS, true);

    //Naming
    result.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

    return result;
}

}

希望有人可以帮忙检查一下,我怎么能得到我期望的回复,真的很感激:)

1 个答案:

答案 0 :(得分:0)

您可以使用@JsonPropertyOrder注释在序列化时设置属性顺序,如下所示。

@JsonPropertyOrder({"name","age","code","time"})
public class Test extends BasicTest{
   private String name;
   private Integer age;

   // ... Getter and Setter
}