I have json
{
"Person": {
"PersonId": 122,
"Name": "John",
"Surname": "Doe",
"age": 2
}
}
I want to convert it to Java class
public class Person {
private String personId;
private String name;
private String surname;
private int age;
//getters,setters...
}
And I don’t have permission to change this Person
class.
What I already have tried is
@Bean
ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new LowerCaseStrategy());
return mapper;
}
public static class LowerCaseStrategy extends PropertyNamingStrategy.PropertyNamingStrategyBase {
@Override
public String translate(String input) {
char[] chars = input.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
}
But it did not help.
Does anyone have an idea how this can be solved?
2
Answers
To convert the JSON with uppercased field names to the desired Java class, you can use the
@JsonProperty
annotation from Jackson library. Here’s how you can modify yourPerson
class and ObjectMapper configuration to achieve the conversion:Person
class to use the@JsonProperty
annotation:LowerCaseStrategy
from your ObjectMapper configuration since the field names in your JSON are already in lowercase.Now, when you deserialize the JSON using the updated ObjectMapper, it will correctly map the fields with uppercased names to the corresponding fields in the
Person
class.For example:
With these changes, the JSON with uppercased field names will be correctly converted to the Java
Person
object.You are almost there. The one error you made, is the direction in which the PropertyNamingStrategy applies: You are converting from Java name, to JSON name, not the other way around. So, this should work:
Also, Jackson has
PropertyNamingStrategies.UPPER_CAMEL_CASE
which should do the thing you need without implementing your own.