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:
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 {
// ...
}