I'm using ObjectMapper in the following situation, however, the Person class has a JSON property of "last_name" which doesn't seem to be getting mapped when the "name" property is mapped fine. I have included my Person class below. Any reasons why this might be happening are appreciated. Jackson core/mapper 1.8.5 being used.
ObjectNode node = (ObjectNode) row.getDocAsNode();
try {
Person person = mapper.readValue(node, Person.class);
tt.setText(person.getName());
bt.setText(person.getLastName());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Person class:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
private String _name;
private String _last_name;
public String getName() { return _name; }
public String getLastName() { return _last_name; }
public void setName(String str) { _name = str; }
public void setLastName(String str) { _last_name = str; }
}
I used @SerializedName("attribute_value_with_underscore") which worked for me
Hope this helps!
More details: https://www.javadoc.io/doc/com.google.code.gson/gson/2.6.2/com/google/gson/annotations/SerializedName.html
Java Bean specification defines what are expected mappings; and so having method
getLastName()
means that only exact property "lastName" would be mapped.To map "last_name", you have couple of options:
@JsonProperty("last_name")
next to get method to rename JSON property usedPropertyNamingStrategy
(likePropertyNamingStrategy. LowerCaseWithUnderscoresStrategy
), registered with "ObjectMapper.setNamingStrategy()" to change how Bean properties are mapping JSON namesLatter method makes sense if all your data comes using naming convention different from Java Bean naming convention (camel case). Former is better for one-off changes.