繁体   English   中英

Jackson ObjectMapper - 未映射带有“_”的属性

[英]Jackson ObjectMapper - properties with “_” not mapped

我在以下情况下使用 ObjectMapper,但是,Person 类具有“last_name”的 JSON 属性,当“name”属性映射良好时,该属性似乎没有被映射。 我在下面包含了我的 Person 类。 任何可能发生这种情况的原因都值得赞赏。 正在使用 Jackson 核心/映射器 1.8.5。

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”。

要映射“last_name”,您有两个选择:

  • 使用@JsonProperty("last_name")旁边的 get 方法来重命名所使用的 JSON 属性
  • 使用PropertyNamingStrategy (如PropertyNamingStrategy. LowerCaseWithUnderscoresStrategy ),注册“ObjectMapper.setNamingStrategy()”来改变 Bean 属性映射 JSON 名称的方式

如果您的所有数据都使用不同于 Java Bean 命名约定(驼峰式大小写)的命名约定,则后一种方法是有意义的。 前者更适合一次性更改。

我使用了对我有用的 @SerializedName("attribute_value_with_underscore")

希望这可以帮助!

更多详情: https : //www.javadoc.io/doc/com.google.code.gson/gson/2.6.2/com/google/gson/annotations/SerializedName.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM