Skip to content
Advertisement

Convert nested map fields to snake case

how to convert all the nested fields of the following object rendered as json to snake_case? Given it’s read as a org.bson.Document, jackson object mapper won’t work as it’s designed for POJOs and it’s not possible to have POJOs here as the records are schema-less

JavaScript

Advertisement

Answer

It can be easily done by adding a custom key serializer to SimpleModule, then register it to ObjectMapper as follows:

Create a class SnakeCaseSerializer which extends JsonSerializer to override serialize() to modify the key from lower camel case to lower underscore case (aka snake case) with Google Guava library – CaseFormat.

JavaScript

Add this class into SimpleModule as custom key serializer, then register the module to your ObjectMapper. (This way is going to change ALL the field names, but it doesn’t matter because the field names belong to first level are already in snake case.)

JavaScript

Console output:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement