Jackson JSON has no problem serializing/deserializing this class:
public class MyClass { public class Nested { public String string; public Nested() {} } public Nested nestedVar; } but on this one:
public class MyClass { class Nested { public String string; public Nested() {} } public Nested nestedVar; public List<Nested> nestedList; } I get this exception when deserializing:
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class test.MyClass$Nested]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?) at [Source: java.io.StringReader@26653222; line: 1, column: 48] (through reference chain: test.MyClass["nestedList"]->java.util.ArrayList[0])
In the first case, Jackson has no problem dealing with an instance of a nested class, but not in the second case.
Must I write a custom deserializer?
Test code (Jackson 2.6.3):
import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; public class ATest { public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); StringWriter sw = new StringWriter(); MyClass myClass = new MyClass(); MyClass.Nested nestedVar = myClass.new Nested(); List<MyClass.Nested> nestedList = new ArrayList<>(); nestedList.add(nestedVar); myClass.nestedList =nestedList; myClass.nestedVar = nestedVar; mapper.writeValue(sw, myClass); System.out.println(sw.toString()); StringReader sr = new StringReader(sw.toString()); MyClass z = mapper.readValue(sr, MyClass.class); } }
staticfor your nested class: it would avoid the issue you have here and the argument "I don't want to make the inner class accessible outside the outer class" is not affected bystatic. CurrentlyNestedis package-private in your example and you could keep it that way.