【问题标题】:Problem with ObjectMapper change my fields nameObjectMapper 的问题更改我的字段名称
【发布时间】:2020-06-25 08:08:28
【问题描述】:

我正在尝试创建一个传递对象并读取所有字段的方法,以便为 null 且为 String 的字段赋予 "" 的值。

问题出现在我的课堂上。我有这个模型:

@Getter
@Setter
@NoArgsConstructor
@ToString
public class AccountModel {

    private String noTotCount;
    private int nTotal;
    private String account;

}

我做了这个方法: 私有 ObjectMapper obMapper = new ObjectMapper();

private Object stringNullToEmpty(Object object) {

    Class<?> clase = object.getClass();
    Map<String, Object> objectMap = obMapper.convertValue(object, new TypeReference<Map<String, Object>>(){});

    for (Field field : clase.getDeclaredFields()) {
        String fieldName = field.getName();
        if(field.getType().equals(String.class) && objectMap.get(fieldName) == null) {
            objectMap.put(field.getName(), "a");

        }
    }

    return obMapper.convertValue(objectMap, clase);

}

当我创建obMapper.convertValue() 时出现错误,因为他正在将我的noTotCount 字段转换为nototCount,所以当您进入条件并尝试put() 时,在包含键 noTotCount 的 objectMap,因为包含 objectMap 的键是 nototCount

为什么 ObjectMapper 将我的 noTotCount 字段转换为 nototCount

【问题讨论】:

  • 请添加您的完整型号。属性的名称是从 getter/setter 派生的,而不是从字段的名称派生的。
  • 在您的代码中,我看到的是 nTotCount,而不是 noTotCount。在我看来,你在打错字。
  • @M.Deinum 这是我的整个模型,我使用 lombok 注释
  • @Babyburger 对不起,我复制粘贴的时候出错了,帖子里已经修改过了

标签: java jackson objectmapper


【解决方案1】:

当您的驼峰式属性具有单个字母作为第一个“单词”时,您遇到了 java bean 命名约定、由 lombok 和 jackson 生成的 getter 名称的问题。详情请见this question

总之,jackson 期望属性(getter 和 setter)因为它们将由 IDE(例如 eclipse)生成:getnTotCount,但我猜 lombok 会生成 getNTotCount(我没有对你的代码进行 de-lombok) .这使得 jackson 失败(通过重命名 getter 来重现)。

解决方法:自己创建 getter 并防止 lombok 生成它@JsonProperty("nTotCount") public String getNTotCount()public String getnTotCount()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多