java - jackson 错误 : no suitable constructor for a simple class

标签 java json jackson

我有麻烦了,这是一个我想用 Jackson 2.3.2 序列化/反序列化的类。 序列化工作正常但不是反序列化。

我有如下异常:

No suitable constructor found for type [simple type, class Series]: can not instantiate from JSON object (need to add/enable type information?)

最奇怪的是,如果我评论构造函数,它会完美地工作!

public class Series {

private int init;
private String key;
private String color;

public Series(String key, String color, int init) {
    this.key = key;
    this.init = init;
    this.color = color;
}

//Getters-Setters

}

还有我的单元测试:

public class SeriesMapperTest {

private String json = "{\"init\":1,\"key\":\"min\",\"color\":\"767\"}";
private ObjectMapper mapper = new ObjectMapper();

@Test
public void deserialize() {
    try {
        Series series = mapper.readValue(json, Series.class);
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}
}

此异常是从 Jackson 库的 BeanDeserializerBase 的方法 deserializeFromObjectUsingNonDefault() 中抛出的。

有什么想法吗?

谢谢

最佳答案

Jackson 没有强制要求类具有默认构造函数。您可以使用 the @JsonCreator annotation 注释现有的构造函数并使用 @JsonProperty 注释将构造函数参数绑定(bind)到属性。 注意:如果您只有一个构造函数,甚至可以抑制 @JsonCreator

这种方法的优点是可以创建真正不可变的对象,这对各种 good reasons 都是好事。 .

这是一个例子:

public class JacksonImmutable {
    public static class Series {

        private final int init;
        private final String key;
        private final String color;

        public Series(@JsonProperty("key") String key,
                      @JsonProperty("color") String color,
                      @JsonProperty("init") int init) {
            this.key = key;
            this.init = init;
            this.color = color;
        }

        @Override
        public String toString() {
            return "Series{" +
                    "init=" + init +
                    ", key='" + key + '\'' +
                    ", color='" + color + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        String json = "{\"init\":1,\"key\":\"min\",\"color\":\"767\"}";
        System.out.println(mapper.readValue(json, Series.class));
    }
}

关于java - jackson 错误 : no suitable constructor for a simple class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25101627/

相关文章:

java - JaCoCo 分支覆盖尝试资源

java - 动态规划 : perfect sum with negative numbers

Python JSON 加载/转储会破坏 Unicode?

python - 删除某些键具有空值的 JSON 对象

java - 使用 Jackson 在 CSV 文件中设置本地化列标题

Java HashSet 同步查询

java - J2ME数据库更新问题

c# - 解析从 Sitecore Item Web API 返回的 JSON

java - jsonrpc4j : How to add type info to parameters?

java - 使用 Jersey 是否可以隐藏某些类别属性?