使用fastxml.jackson将带有重载的setter的对象反序列化 [英] Deserializing to object with overloaded setter with fasterxml.jackson

查看:143
本文介绍了使用fastxml.jackson将带有重载的setter的对象反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将json字符串反序列化为对象,该对象的字段的setter重载了.我不想使用@JsonIgnore显式注释设置器之一. 为什么Jackson图书馆无法根据在json字符串中获取的值的类型使用适当的setter? 以下是代码:

I want to deserialize json string into object which have overloaded setter for a field. I don't want to explicitly annotate one of the setter with @JsonIgnore. Why can't jackson library use appropriate setter according to the type of value it fetches in json string? Following is Code:

public class A {

Set<Integer> set = new HashSet<Integer>();

public Set<Integer> getSet() {
    return set;
}

public void setSet(Set<Integer> set) {
    this.set = set;
}

public void setSet(String str)
{
    this.set = null;
}
}
=========================
String input = "{\"set\":[1,4,6]}";

A b = mapper.readValue(input, A.class);

System.out.println(b.getSet());

我遇到以下错误:

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_ARRAY token
 at [Source: (String)"{"set":[1,4,6]}"; line: 1, column: 8] (through reference chain: com.rs.multiplesetter.A["set"])

推荐答案

Jackson不接受multiple setter.您需要通过@JsonSetter指定一个setter.如果要接受多种类型,则可以使用JsonNode进行处理.这是示例:

Jackson not accept multiple setter. You need to specify the one setter by @JsonSetter. If you want to accept multiple type then you can handle this using JsonNode. Here is example:

public class A implements Serializable{

private static final long serialVersionUID = 1L;

Set<Integer> set = new HashSet<Integer>();

public Set<Integer> getSet() {
    return set;
}

public void setSet(Set<Integer> set) {
    this.set = set;
}

public void setSet(String str)
{
    this.set = null;
}

@JsonSetter
public void setSet(JsonNode jsonNode){
     //handle here as per your requirement
    if(jsonNode.getNodeType().equals(JsonNodeType.STRING)){
        this.set = null;
    }else if(jsonNode.getNodeType().equals(JsonNodeType.ARRAY)){
        try{
            ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Set<Integer>>() {});
            this.set = reader.readValue(jsonNode);
        }catch (Exception ex){
        }
    }
}
}

**如果您不想在这里处理,则可以使用自定义反序列化类.

**If you dont want to handle here then you can use custom deserialization class.

这篇关于使用fastxml.jackson将带有重载的setter的对象反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆