Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jackson @JsonProperty("SoMeVaLuE") to ignore case

What I am trying to achieve:

Parse a json using Jackson and JsonProperty, however, the key, while always the same, comes in all flavor of upper lower cases.

What I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The input json has a field {"field": "value"}

Therefore, in my POJO, I do this:

public record MyPojo(@JsonProperty("field") String field

This works, but then, the key comes in different flavor of cases.

i.e. {"fieLd": "value"} {"Field": "value"} {"fIEld": "value"} etc

For now, I use the @JsonAlias("fieLd") etc…

But this is not scalable, since there are many permutations of cases.

Question:

How to tell Jackson and the JsonProperty to simply ignore the case?

>Solution :

i suggest putting the json to some kind of pre-processing-step to normalize property Names before Jackons does its json to object mapping

public class CustomDeserializer extends JsonDeserializer<MyObject> {
   @Override
   public MyObject deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
       ObjectCodec codec = jsonParser.getCodec();
       JsonNode node = codec.readTree(jsonParser);
       ObjectNode normalizedNode = JsonNodeFactory.instance.objectNode();

       // Normalize property names
       Iterator<String> fieldNames = node.fieldNames();
       while (fieldNames.hasNext()) {
           String originalPropertyName = fieldNames.next();
           String normalizedPropertyName = normalizePropertyName(originalPropertyName);
           normalizedNode.set(normalizedPropertyName, node.get(originalPropertyName));
       }

       ObjectMapper mapper = (ObjectMapper) codec;
       JsonParser modifiedJsonParser = mapper.treeAsTokens(normalizedNode);
       return mapper.readValue(modifiedJsonParser, MyObject.class);
   }

   private String normalizePropertyName(String propertyName) {
       // Perform your normalization logic here
       // For example, convert to lowercase or replace spaces with underscores
       return propertyName.toLowerCase().replaceAll(" ", "_");
   }
}

and then wire up the deserializer as you see fit, for example by annotating the target Class

@JsonDeserialize(using = CustomDeserializer.class)
public class MyObject {
    // ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading