1

我有一个类正在扩展一些库类。如何将类属性扩展为驼峰式。

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
class Test extends Abc {
}



// Library class which I can't modify
class Abc {
  private firstName;
 }

如何将firstName设为first_name

4

1 回答 1

0

你可以使用 mixin 。基本上,您在另一个类上定义注释,然后将真实类与 objectMapper 中的 mixin 相关联

public class JacksonMixin {
    @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
    @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
    abstract class MixinAbc{}

    // Library class which I can't modify
    class Abc {
      private String firstName;

     }

    @Test
    public void testMixin() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.addMixIn(Abc.class, MixinAbc.class);
        Abc value = new Abc();
        value.firstName="bill";
        String writeValueAsString = objectMapper.writeValueAsString(value);
        Assert.assertEquals("{\"first_name\":\"bill\"}", writeValueAsString);

    }

}

编辑: addMixInAnnotation 已弃用,现在只是 addMixIn 。

于 2019-08-20T13:45:28.637 回答