0

i am trying to use PropertyNamingStrategy.SNAKE_CASE to convert a Map<String, Object> from CamelCase to Snake_Case - but without sucess. It is a "generic" MAP. Anyone can help me?

My class example:

   private ResponseEntity<Class> doPostRequest(Map<String, Object> payload) {
        
        ObjectMapper payloadConversor = new ObjectMapper();
        
        payloadConversor.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);      
        
        Map<String, Object> payloadConverted = payloadConversor
                .convertValue(payload, new TypeReference<Map<String, Object>>() {});  

} 

Thank you!

Renan
  • 1

1 Answers1

0

Renan. The example you showed isn't working because ObjectMapper does not consider a map key being a property. It only converts names of class fields. For example:

@Data
@AllArgsConstructor
public static class MyClass {
    private String myString;
}

System.out.println(objectMapper.writeValueAsString(new MyClass("asdfasdgADFAasdf")));

result: {"my_string":"asdfasdgADFAasdf"}

I could suggest that you take a look at a related question Converting a string from snake case to camel case in Java. Here you will find ways to convert strings to different case formats. Then you could just iterate through your map keys and convert them.

Hope you find this helpful!

Igor
  • 91
  • 3