简体   繁体   中英

JAVA - Not converting CamelCase to Snake_Case using ObjectMapping and SetPropertyNamingStrategy - SNAKE_CASE

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. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM