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.
In order to fix this, make the MyObject
inner class static:
public static class MyObject {
public int value1;
public String value2;
}
Without the static keyword, the inner class needs an instance of the encompassing outer class in order to exist. This is what causes the exception.
For the enum
that is not the case because inner enums are implicitly static, see the Java Language Specification, chapter 8.9