簡體   English   中英

如何將 JSON 密鑰從駝峰式大小寫更改為 POJO 的蛇式大小寫?

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

我正在使用 Wiremock 進行測試,並且我有以下 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;
      }
    }

我正在存根一些外部 API,這些 API 應該將此 POJO 作為 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)));

問題是當我使用 ObjectMapper 進行序列化時,我得到“timeSeries”而不是“time_series”。 有什么方法可以僅通過更改測試文件來獲得正確的 JSON 字符串格式?

timeSeriesSupply字段,您應該更改@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) ,移動到Supply類,如下所示

    @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;
      }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM