Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change JSON key from camelCase to snake case for POJO?

Tags:

java

wiremock

I am doing testing with Wiremock and I have following example for POJO:

 @Data
    public class DataResponse {
      private Supply supply;
      private static class Supply {
        private List<TimeSeries> timeSeries;
      }
      @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
      public  static class TimeSeries {
         private LocalDate date;
      }
    }

And I am stubbing some external API which should response with this POJO as json:

DataResponse dataResponse = DataResponse.builder()
   .supply(DataResponse.Supply.builder()
       .timeSeries(List.of(
           DataResponse.TimeSeries.builder()
             .date("2021-11-16")
              build()
        ))
        .build()
   .build()
 
 String jsonDataResponse = mapper.writeValueAsString(dataResponse); //mapper is instance of ObjectMapper
 
 stubFor(WireMock.get(urlEqualTo("/someUrl"))
     .willReturn(aResponse()
        .withBody(jsonDataResponse)));

The issue is when I do serialization with ObjectMapper I get "timeSeries" instead of "time_series". Is there any way to get the right JSON string format only with changes in the test file?

like image 209
Ulukbek Abylbekov Avatar asked Oct 21 '25 04:10

Ulukbek Abylbekov


1 Answers

timeSeries is field of Supply, you should change place of @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class), move to Supply class like below

    @Data
    public class DataResponse {
      private Supply supply;
      @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
      private static class Supply {
        private List<TimeSeries> timeSeries;
      }
      public  static class TimeSeries {
         private LocalDate date;
      }
    }
like image 53
divilipir Avatar answered Oct 22 '25 18:10

divilipir