1

I have a class which is extending some library class. How to make extending class properties to camel case.

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



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

How to make firstName as first_name

Ramesh Papaganti
  • 7,311
  • 3
  • 31
  • 36

1 Answers1

0

You could use mixin . Basically, you define your annotation on another class, then associate the real class to your mixin in your objectMapper

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);

    }

}

edit: addMixInAnnotation is deprecated, it's just addMixIn now.

pdem
  • 3,880
  • 1
  • 24
  • 38