2022-12-16

Non-static inner classes like this can only by instantiated using default, no-argument constructor error when deserialize

I am trying to serialize and deserialize my object but I got an error during deserialization:

Cannot construct an instance of 'MyObject' (although at least one Creator exists): 
non-static inner classes like this can only be instantiated using a default, no-argument constructor.

I had constructor for class MyObject with 2 parameters but I changed it to default constructor, but it still throw the same error.

This is my code:

@Test
public void serializeAndDeserializeTest() throws JsonProcessingException {
    var list = new MyObject[2];
    var t1 = new MyObject();
    t1.value1 = TestEnum.VALUE5.numVal;
    t1.value2 = "A";
    var t2 = new MyObject();
    t2.value1 = TestEnum.VALUE1.numVal;
    t2.value2 = "B";
    list[0] = t1;
    list[1] = t2;
    var mapper = new ObjectMapper();
    var json = mapper.writeValueAsString(list);
    MyObject[] output = mapper.readValue(json, MyObject[].class);
}

public class MyObject
{
    public int value1;
    public String value2;
}

public enum TestEnum
{
    VALUE1(1),
    VALUE3(3),
    VALUE5(5);

    public int numVal;

    TestEnum(int numVal) {
        this.numVal = numVal;
    }
}

I also tried to create a private default constructor but it doesn't work.



No comments:

Post a Comment