Jackson ObjectMapper - 带有“_”的属性没有映射 [英] Jackson ObjectMapper - properties with "_" not mapped

查看:761
本文介绍了Jackson ObjectMapper - 带有“_”的属性没有映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下情况下使用ObjectMapper,但是,Person类的JSON属性为last_name,当name属性映射正常时,它似乎没有被映射。我在下面列出了我的Person类。任何可能发生这种情况的原因都值得赞赏。正在使用Jackson core / mapper 1.8.5。

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

人员类:

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

}


推荐答案

Java Bean规范定义了预期映射的内容;因此,方法 getLastName()意味着只会映射精确属性lastName。

Java Bean specification defines what are expected mappings; and so having method getLastName() means that only exact property "lastName" would be mapped.

要映射 last_name,你有几个选择:

To map "last_name", you have couple of options:


  • 使用 @JsonProperty(last_name)在get方法旁边重命名使用的JSON属性

  • 使用 PropertyNamingStrategy (如 PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy ),使用ObjectMapper.setNamingStrategy()注册以更改Bean属性映射JSON名称的方式

  • 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

后期如果所有数据都使用与Java Bean命名约定不同的命名约定(camel case),则该方法是有意义的。前者对于一次性更改更好。

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.

这篇关于Jackson ObjectMapper - 带有“_”的属性没有映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆