Jackson ObjectMapper - properties with “_” not map

2020-03-08 03:38发布

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; }

}

2条回答
Deceive 欺骗
2楼-- · 2020-03-08 03:51

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

查看更多
走好不送
3楼-- · 2020-03-08 04:05

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:

  • use @JsonProperty("last_name") next to get method to rename JSON property used
  • use a PropertyNamingStrategy (like PropertyNamingStrategy. LowerCaseWithUnderscoresStrategy), registered with "ObjectMapper.setNamingStrategy()" to change how Bean properties are mapping JSON names

Latter 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.

查看更多
登录 后发表回答