23

I have tried to test the following code with no success:

class TestClass
{
  private class ND2Customer
  {
    public String name;
    public String description;
    public String email;
    public Boolean multiuser;

    public String dnszone;
    public String uri;
    public String type;

    public ND2Customer()
    {

    }
  }

  @Test
  public void TestJackson() throws JsonParseException, JsonMappingException, IOException
  {
    String json="{\"description\": \"test1u\", \"dnszone\": \"test1.public.sevenltest.example.com.\", \"uri\": \"http://199.127.129.69/customer/test1\", \"multiuser\": true, \"type\": \"2.0.3-3146\", \"email\": \"test1@com.com\", \"name\": \"test1\"}";
    ObjectMapper mapper = new ObjectMapper();

    ND2Customer casted=mapper.readValue(json, ND2Customer.class);

    String castedback=mapper.defaultPrettyPrintingWriter().writeValueAsString(casted);
    System.out.println(castedback);
  } 
}

This problem is different from this one: Deserializing JSON with Jackson - Why JsonMappingException "No suitable constructor"?

and this one: JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

and this one: JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

as I have manually override the default constructor, and its not a subclass.

How do I fix this problem?

Community
  • 1
  • 1
tribbloid
  • 4,026
  • 14
  • 64
  • 103

2 Answers2

58

Make it static. Jackson can not deserialize to inner classes

eugen
  • 5,856
  • 2
  • 29
  • 26
  • 2
    Thanks, it works. Your solution perfectly makes sense, as Jackson mapper cannot initialize an inner class and return it. – tribbloid Oct 16 '12 at 19:34
  • 3
    Minor addition: Jackson can actually deserialize one kind of non-static inner classes -- those referenced directly by the parent class. But this is not the case here, as Test class is not being serialized. In this case non-staticness was probably accidental. – StaxMan Oct 17 '12 at 17:21
  • 2
    I would bet most of the "No suitable constructor" issues with nested POJOs are because of forgetting to mark it static. Thanks eugen! – Kirk B. Mar 20 '13 at 23:29
1

The problem is probably that Jackson can't properly reach your ND2Customer class to invoke its constructor because it is private, as your class otherwise looks just fine. Try making it public and seeing if that works.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215