如何使用Jackson对多个案例进行反序列化

时间:2016-10-25 06:55:13

标签: java json jackson objectmapper

我正在使用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);

我在任何地方都找不到任何解决方案。如果有人能帮助你如何继续下去将会很好。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您可以为第二个字段名称添加第二个带有@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中存在两个属性,它们将被覆盖。