【问题标题】:How to deserialize multiple cases with Jackson如何使用 Jackson 反序列化多个案例
【发布时间】:2016-10-25 06:55:12
【问题描述】:

我正在使用 jackson-core-2.8.3,并且我有一个 json,它在多种情况下都提供了元素。我想将它映射到我的班级,但我不能这样做,因为我的班级中只能有一种 PropertyNamingStratergy。

Json 示例:-

{"tableKey": "1","not_allowed_pwd": 10}

可以有另一个json像

{"tableKey": "1","notAllowedPwd": 10}

ClassToMap :-

class MyClass {
public String tableKey;
public Integer notAllowedPwd;
}

ObjectMapper 代码:-

ObjectMapperobjectMapper=new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES,true);
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.setVisibility(PropertyAccessor.ALL,Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD,Visibility.ANY);
MyClass obj = objectMapper.readValue(s, MyClass.class);

我在任何地方都找不到任何解决方案。如果有人可以帮助如何继续,那就太好了。

【问题讨论】:

标签: java json jackson objectmapper


【解决方案1】:

使用 jackson-annotations 库并添加 @JsonProperty 如下。

class MyClass {
  public String tableKey;
  @JsonProperty("not_allowed_pwd")
  public Integer notAllowedPwd;
}

【讨论】:

  • 谢谢,但我有不同的要求,我已经编辑了问题。
  • 在这种情况下,您要么必须 1) 映射到两个不同的类并手动组合,要么 2) 修复 json 的架构。我不认为可以毫不费力地映射更改/不一致的属性名称
  • 是否有任何在 readValue 方法中使用的类,我可以使用我的类将属性名称修改为驼峰式
【解决方案2】:

您可以为第二个字段名称添加带有 @JsonProperty 注释的第二个 setter:

class MyClass {
    private String tableKey;
    private Integer notAllowedPwd;

    public String getTableKey() {
        return tableKey;
    }

    public void setTableKey(String tableKey) {
        this.tableKey = tableKey;
    }

    public Integer getNotAllowedPwd() {
        return notAllowedPwd;
    }

    public void setNotAllowedPwd(Integer notAllowedPwd) {
        this.notAllowedPwd = notAllowedPwd;
    }

    @JsonProperty("not_allowed_pwd")
    public void setNotAllowedPwd2(Integer notAllowedPwd) {
        this.notAllowedPwd = notAllowedPwd;
    }
}

考虑到如果json中存在这两个属性,它们将被覆盖。

【讨论】:

    猜你喜欢
    • 2015-03-31
    • 2013-08-04
    • 2012-11-18
    • 2015-05-20
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    相关资源
    最近更新 更多