I have some Pojo classes which are generated through avro schema. The problem is that the field name in the schema is declared with the first character as a capital letter. I am receiving a JSON string and in a JSON string also each key name starts with a capital letter, due to which Jackson is not able to map the data.
Is there any way we can override the logic of the Jackson parser to find the getter/setter in pojo with just get + FieldName and set + FieldName.
Bellow is the sample POJO class and JSON which I am trying to parse.
POJO:
public class Sample {
private java.lang.CharSequence Field1;
private java.lang.CharSequence Field2;
private java.lang.CharSequence Field3;
public java.lang.CharSequence getField1() {
return Field1;
}
public void setField1(java.lang.CharSequence Field1) {
this.Field1 = Field1;
}
public java.lang.CharSequence getField2() {
return Field2;
}
public void setField2(java.lang.CharSequence Field2) {
this.Field2 = Field2;
}
public java.lang.CharSequence getField3() {
return Field3;
}
public void setField3(java.lang.CharSequence Field3) {
this.Field3 = Field3;
}
}
JSON:
{
"Field1": "Value1",
"Field2": "Value2",
"Field3": "Value3"
}
Code to parse the JSON:
String json = = "";
ObjectMapper objectMapper = new ObjectMapper();
Sample sample = objectMapper.readValue(json, Sample.class);
If I pass the below JSON then it’s working perfectly fine.
{
"field1": "Value1",
"field2": "Value2",
"field3": "Value3"
}
But I am receiving the JSON in the previous format and I don’t want to write a code to convert each JSON key’s first character into lowercase (which would still create an issue for some fields where more than one starting letter is capital).
2
Answers
Here’s an updated version of your Sample class with the @JsonProperty annotations:
Now, when you parse the JSON using the ObjectMapper, it should work correctly without manually converting the JSON keys to lowercase:
You should be able to utilise Jackson’s MixIn feature to implement an abstract class or interface that provides getter methods that are seen in the Sample class. Then you can apply @JsonProperty annotations to the interface getter methods and apply the MixIn to your objectMapper. You can take a look here. See also
You could try:
Then when you call your object mapper: