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

dxxyhpgq  于 2022-11-08  发布在  其他
关注(0)|答案(3)|浏览(135)

我正在使用jackson-core-2.8.3,我有一个json,它在多个情况下提供了元素。我想将它Map到我的类,但我不能这样做,因为我只能在我的类中有一种类型的PropertyNamingStratergy。
示例Json:-

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

可以有另一个json,如

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

类到Map:-

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

对象Map器代码:-

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

我在任何地方都找不到任何解决办法。如果有人能帮助如何进行,那将是很好的。

iswrvxsc

iswrvxsc1#

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

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

ia2d9nvy2#

您可以有第二个setter,其中第二个字段名称为@JsonProperty注解:

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中,它们将被覆盖。

b4lqfgs4

b4lqfgs43#

在字段上使用这些注解:

@JsonProperty("not_allowed_pwd")
@JsonAlias("notAllowedPwd")
public Integer notAllowedPwd;

相关问题