简体   繁体   中英

How to get Jackson to ignore constructorproperties

I'm trying to get Jackson to deserialize

{
    "test": 2018
}

to

SomeJavaClass:
 private final Test test

But I want to make my Test class using Project Lombok. However Lombok annotates the class with ConstructorProperties, and for some reason this makes jackson fail.

My classes looks like this:

@Value
public class SomeJavaClass {
    Test test;
}


@Value
public class Test{
    String value;
}

Test is delomboked as:

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() + ")";
    }
}

Is it possible to make Jackson ignore the constructorproperties somehow?

I also think that the problem here is not the annotation @java.beans.ConstructorProperties({"value"}) .

Based on your delombok it seems that you have a set of annotations that will prevent default constructor to form.

So maybe you get rid of this problem by adding @NoArgsConstructor . Without default constructor and having no @JsonCreator s you will have an error like:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of org.example.spring.jackson.JacksonTest$TestClass (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)

The reason why this fails is not the @ConstructorProperties . In fact, this annotation is required to make Jackson work with Lombok's @AllArgsConstructor .

The problem here is that the value of test in your JSON is an integer, but your class structure requires it to be an object. So you have to make the field test in SomeJavaClass an int . Then you also don't need the Test class. (Or rename value to test in Test and get rid of SomeJavaClass and deserialize to Test .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM