【问题标题】:How to get Jackson to ignore constructorproperties如何让杰克逊忽略构造函数属性
【发布时间】:2018-11-12 12:09:59
【问题描述】:

我正在尝试让 Jackson 反序列化

{
    "test": 2018
}

SomeJavaClass:
 private final Test test

但我想使用 Project Lombok 制作我的测试类。然而,Lombok 使用 ConstructorProperties 注释该类,并且由于某种原因这使得杰克逊失败。

我的课程如下所示:

@Value
public class SomeJavaClass {
    Test test;
}


@Value
public class Test{
    String value;
}

测试被分解为:

public class Test {
    int value;

    @java.beans.ConstructorProperties({"value"})
    public Test(final int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }

    public boolean equals(final Object o) {
        if (o == this) {
            return true;
        }
        if (!(o instanceof Test)) {
            return false;
        }
        final Test other = (Test) o;
        if (this.getValue() != other.getValue()) {
            return false;
        }
        return true;
    }

    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        result = result * PRIME + this.getValue();
        return result;
    }

    public String toString() {
        return "Test(value=" + this.getValue() + ")";
    }
}

是否有可能让杰克逊以某种方式忽略构造函数属性?

【问题讨论】:

标签: java jackson lombok


【解决方案1】:

我也觉得这里的问题不在于注解@java.beans.ConstructorProperties({"value"})

根据您的 delombok,您似乎有一组注释会阻止默认构造函数的形成。

所以也许你可以通过添加@NoArgsConstructor 来解决这个问题。如果没有默认构造函数并且没有@JsonCreators,您将遇到如下错误:

com.fasterxml.jackson.databind.exc.MismatchedInputException: 不能 构造 org.example.spring.jackson.JacksonTest$TestClass 的实例 (尽管至少存在一个 Creator):不能从 Object 反序列化 值(无委托或基于属性的创建者)

【讨论】:

    【解决方案2】:

    失败的原因不是@ConstructorProperties。事实上,需要这个注解才能让 Jackson 使用 Lombok 的 @AllArgsConstructor

    这里的问题是你的JSON中test的值是一个整数,但是你的类结构要求它是一个对象。所以你必须将test 中的SomeJavaClass 字段设为int。那么你也不需要Test 类。 (或者将Test中的value重命名为test,去掉SomeJavaClass,反序列化为Test。)

    【讨论】:

      猜你喜欢
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2016-04-19
      相关资源
      最近更新 更多