If you have a few years of experience in the Java ecosystem, and you're interested in sharing that experience with the community (and getting paid for your work of course), have a look at the "Write for Us" page. Cheers. Eugen

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll go over the most common Jackson Exceptions – the JsonMappingException and UnrecognizedPropertyException.

Finally – we’ll briefly discuss Jackson no such method errors.

2. “JsonMappingException: Can not construct instance of”

2.1. The Problem

First – let’s take a look at JsonMappingException: Can not construct instance of.

This exception is thrown if Jackson can’t create an instance of the class – this happens if the class is abstract or it is just an interface.

In the following example – we try to deserialize an instance from class Zoo which has a property animal with abstract type Animal:

public class Zoo {
    public Animal animal;
    
    public Zoo() { }
}

abstract class Animal {
    public String name;
    
    public Animal() { }
}

class Cat extends Animal {
    public int lives;
    
    public Cat() { }
}

When we try to deserialize a JSON String to Zoo instance it throws the “JsonMappingException: Can not construct instance of” as in the following example:

@Test(expected = JsonMappingException.class)
public void givenAbstractClass_whenDeserializing_thenException() 
  throws IOException {
    String json = "{"animal":{"name":"lacy"}}";
    ObjectMapper mapper = new ObjectMapper();

    mapper.reader().forType(Zoo.class).readValue(json);
}

The full exception is:

com.fasterxml.jackson.databind.JsonMappingException: 
Can not construct instance of org.baeldung.jackson.exception.Animal,
  problem: abstract types either need to be mapped to concrete types, 
  have custom deserializer, 
  or be instantiated with additional type information
  at 
[Source: {"animal":{"name":"lacy"}}; line: 1, column: 2] 
(through reference chain: org.baeldung.jackson.exception.Zoo["animal"])
	at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)

2.2. The Solution

We can solve the problem with a simple annotation – @JsonDeserialize on the abstract class:

@JsonDeserialize(as = Cat.class)
abstract class Animal {...}

3. JsonMappingException: No suitable constructor

3.1. The Problem

Now – let’s look at the common JsonMappingException: No suitable constructor found for type.

This exception is thrown if Jackson can’t access the constructor.

In the following example – class User doesn’t have a default constructor:

public class User {
    public int id;
    public String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

When we try to deserialize a JSON String to User an Exception “JsonMappingException: No suitable constructor found” is thrown – as in the following example:

@Test(expected = JsonMappingException.class)
public void givenNoDefaultConstructor_whenDeserializing_thenException() 
  throws IOException {
    String json = "{"id":1,"name":"John"}";
    ObjectMapper mapper = new ObjectMapper();

    mapper.reader().forType(User.class).readValue(json);
}

The full exception is:

com.fasterxml.jackson.databind.JsonMappingException: 
No suitable constructor found for type 
[simple type, class org.baeldung.jackson.exception.User]:
 can not instantiate from JSON object (need to add/enable type information?)
 at [Source: {"id":1,"name":"John"}; line: 1, column: 2]
        at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)

3.2. The Solution

To solve this problem – just add a default constructor as in the following example:

public class User {
    public int id;
    public String name;

    public User() {
        super();
    }

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

Now when we deserialize – the process will work just fine:

@Test
public void givenDefaultConstructor_whenDeserializing_thenCorrect() 
  throws IOException {
 
    String json = "{"id":1,"name":"John"}";
    ObjectMapper mapper = new ObjectMapper();

    User user = mapper.reader()
      .forType(User.class).readValue(json);
    assertEquals("John", user.name);
}

4. JsonMappingException: Root name does not match expected

4.1. The Problem

Next – let’s take a look at JsonMappingException: Root name does not match expected.

This exception is thrown if the JSON doesn’t match exactly what Jackson is looking for; for example, the main JSON could be wrapped as in the following example:

@Test(expected = JsonMappingException.class)
public void givenWrappedJsonString_whenDeserializing_thenException()
  throws IOException {
    String json = "{"user":{"id":1,"name":"John"}}";

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

    mapper.reader().forType(User.class).readValue(json);
}

The full exception is:

com.fasterxml.jackson.databind.JsonMappingException:
Root name 'user' does not match expected ('User') for type
 [simple type, class org.baeldung.jackson.dtos.User]
 at [Source: {"user":{"id":1,"name":"John"}}; line: 1, column: 2]
   at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)

4.2. The Solution

We can solve this problem using the annotation @JsonRootName – as in the following example:

@JsonRootName(value = "user")
public class UserWithRoot {
    public int id;
    public String name;
}

When we try to deserialize the wrapped JSON – it works correctly:

@Test
public void 
  givenWrappedJsonStringAndConfigureClass_whenDeserializing_thenCorrect() 
  throws IOException {
 
    String json = "{"user":{"id":1,"name":"John"}}";

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

    UserWithRoot user = mapper.reader()
      .forType(UserWithRoot.class)
      .readValue(json);
    assertEquals("John", user.name);
}

5. JsonMappingException: No serializer found for class

5.1. The Problem

Now – let’s take a look at JsonMappingException: No serializer found for class.

This exception is thrown if you try to serialize an instance while its properties and their getters are private.

In the following example – we try to serialize a “UserWithPrivateFields“:

public class UserWithPrivateFields {
    int id;
    String name;
}

When we try to serialize an instance of “UserWithPrivateFields” – an Exception “JsonMappingException: No serializer found for class” is thrown as in the following example:

@Test(expected = JsonMappingException.class)
public void givenClassWithPrivateFields_whenSerializing_thenException() 
  throws IOException {
    UserWithPrivateFields user = new UserWithPrivateFields(1, "John");

    ObjectMapper mapper = new ObjectMapper();
    mapper.writer().writeValueAsString(user);
}

The full exception is:

com.fasterxml.jackson.databind.JsonMappingException: 
No serializer found for class org.baeldung.jackson.exception.UserWithPrivateFields
 and no properties discovered to create BeanSerializer 
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
  at c.f.j.d.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59)

5.2. The Solution

We can solve this problem by configuring the ObjectMapper visibility – as in the following example:

@Test
public void givenClassWithPrivateFields_whenConfigureSerializing_thenCorrect() 
  throws IOException {
 
    UserWithPrivateFields user = new UserWithPrivateFields(1, "John");

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

    String result = mapper.writer().writeValueAsString(user);
    assertThat(result, containsString("John"));
}

Or using the annotation @JsonAutoDetect – as in the following example:

@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class UserWithPrivateFields { ... }

Of course, if we do have the option to modify the source of the class, we can also add in getters for Jackson to use.

6. JsonMappingException: Can not deserialize instance of

6.1. The Problem

Next – let’s take a look at JsonMappingException: Can not deserialize instance of.

This exception is thrown if the wrong type is used while deserializing.

In the following example – we are trying to deserialize a List of User:

@Test(expected = JsonMappingException.class)
public void givenJsonOfArray_whenDeserializing_thenException() 
  throws JsonProcessingException, IOException {
 
    String json 
      = "[{"id":1,"name":"John"},{"id":2,"name":"Adam"}]";
    ObjectMapper mapper = new ObjectMapper();
    mapper.reader().forType(User.class).readValue(json);
}

The full exception is:

com.fasterxml.jackson.databind.JsonMappingException:
Can not deserialize instance of 
  org.baeldung.jackson.dtos.User out of START_ARRAY token
  at [Source: [{"id":1,"name":"John"},{"id":2,"name":"Adam"}]; line: 1, column: 1]
  at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)

6.2. The Solution

We can solve this problem by changing the type from User to List<User> – as in the following example:

@Test
public void givenJsonOfArray_whenDeserializing_thenCorrect() 
  throws JsonProcessingException, IOException {
 
    String json
      = "[{"id":1,"name":"John"},{"id":2,"name":"Adam"}]";
   
    ObjectMapper mapper = new ObjectMapper();
    List<User> users = mapper.reader()
      .forType(new TypeReference<List<User>>() {})
      .readValue(json);

    assertEquals(2, users.size());
}

7. UnrecognizedPropertyException

7.1. The Problem

Now – let’s see the UnrecognizedPropertyException.

This exception is thrown if there is an unknown property in the JSON String while deserializing.

In the following example – we try to deserialize a JSON String with extra property “checked“:

@Test(expected = UnrecognizedPropertyException.class)
public void givenJsonStringWithExtra_whenDeserializing_thenException() 
  throws IOException {
 
    String json = "{"id":1,"name":"John", "checked":true}";

    ObjectMapper mapper = new ObjectMapper();
    mapper.reader().forType(User.class).readValue(json);
}

The full exception is:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "checked" (class org.baeldung.jackson.dtos.User),
 not marked as ignorable (2 known properties: "id", "name"])
 at [Source: {"id":1,"name":"John", "checked":true}; line: 1, column: 38]
 (through reference chain: org.baeldung.jackson.dtos.User["checked"])
  at c.f.j.d.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:51)

7.2. The Solution

We can solve this problem by configuring the ObjectMapper – as in the following example:

@Test
public void givenJsonStringWithExtra_whenConfigureDeserializing_thenCorrect() 
  throws IOException {
 
    String json = "{"id":1,"name":"John", "checked":true}";

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    User user = mapper.reader().forType(User.class).readValue(json);
    assertEquals("John", user.name);
}

Or we can use the annotation @JsonIgnoreProperties:

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {...}

8. JsonParseException: Unexpected character (”’ (code 39))

8.1. The Problem

Next – let’s discuss JsonParseException: Unexpected character (”’ (code 39)).

This exception is thrown if the JSON String to be deserialized contains single quotes instead of double quotes.

In the following example – we try to deserialize a JSON String containing single quotes:

@Test(expected = JsonParseException.class)
public void givenStringWithSingleQuotes_whenDeserializing_thenException() 
  throws JsonProcessingException, IOException {
 
    String json = "{'id':1,'name':'John'}";
    ObjectMapper mapper = new ObjectMapper();

    mapper.reader()
      .forType(User.class).readValue(json);
}

The full exception is:

com.fasterxml.jackson.core.JsonParseException:
Unexpected character (''' (code 39)): 
  was expecting double-quote to start field name
  at [Source: {'id':1,'name':'John'}; line: 1, column: 3]
  at c.f.j.core.JsonParser._constructError(JsonParser.java:1419)

8.2. The Solution

We can solve this by configuring the ObjectMapper to allow single quotes:

@Test
public void 
  givenStringWithSingleQuotes_whenConfigureDeserializing_thenCorrect() 
  throws JsonProcessingException, IOException {
 
    String json = "{'id':1,'name':'John'}";

    JsonFactory factory = new JsonFactory();
    factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
    ObjectMapper mapper = new ObjectMapper(factory);

    User user = mapper.reader().forType(User.class)
      .readValue(json);
 
    assertEquals("John", user.name);
}

9. Jackson NoSuchMethodError

Finally – let’s quickly discuss the Jackson “No such method” errors.

When java.lang.NoSuchMethodError Exception is thrown, it is usually because you have multiple (and incompatible) versions of Jackson jars on your classpath.

The full exception is:

java.lang.NoSuchMethodError:
com.fasterxml.jackson.core.JsonParser.getValueAsString()Ljava/lang/String;
 at c.f.j.d.deser.std.StringDeserializer.deserialize(StringDeserializer.java:24)

10. Conclusion

In this article, we did a deep dive in the most common Jackson problems – exceptions and errors, looking at the potential causes and at the solutions for each one.

The implementation of all these examples and code snippets can be found on Github – this is a Maven-based project, so it should be easy to import and run as it is.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

Sort by:   newest | oldest | most voted
Kishore
Guest

There is one more case:

Can not instantiate value of type [simple type, class com.test.TestClass] from String value (”); no single-String constructor/factory method

What would be solution for this case?

Eugen Paraschiv
Guest

Hey Kishore – there are many more cases, definitely. This is by no means an exhaustive list – just the top ones.
As for your particular issue, beyond just repeating what the error message states – there’s no way of knowing what the root cause is without the actual code.
My suggestion is to have a test that actually reproduces the problem and ask the question on StackOverflow. Then send me the link and I’d be happy to have a look. Cheers,
Eugen.

Dennis Gesker
Guest

Hi Eugen:

How about an error like…

com.fasterxml.jackson.databind.JsonMappingException: Multiple back-reference properties with name ‘myObject’

I have an object that has several (quite a few acutally) OneToMany relationships with other objects
So I have several getters with decorations like…

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy=”myObject”)
@JsonBackReference(value=”myObject”) <– This seems the issue but shouldn't it match the mappedBy?

BTW, great site.

Dennis Gesker
Guest

Scratch this one… I think I had @JsonBackReference and @JsonManagedReference reversed in my classes. Added a @JsonIgnoreProperties(ignoreUnknown=true, value={“hibernateLazyInitializer”, “handler”}) and now I’m running smoothly.

Eugen Paraschiv
Guest

Hey Dennis – glad you’re enjoying the site.
To (somewhat) answer your question – there are so many exceptions that can and do occur with Jackson – this article only focuses on the most common ones and as in no way an exhaustive list.
I’d be happy to have a look at this one, but I’ll need running code to do so (that’s why I always suggest StackOverflow – because they have clear requirements about example code).
So, either post the question there and email me a link, or just email me the example code reproducing the issue.
Cheers
Eugen.

Padma
Guest

Is there a work-around when the object returned is a Spring framework class (org.springframework.security.oauth2.provider.OAuth2Authentication) and there is no default constructor available? I am getting the com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type
Thanks

Eugen Paraschiv
Guest

If you need to marshall the OAuth2Authentication (although that’s something I’d have a second look at) – you can use the Creators feature in Jackson – that should allow you to work with 3rd party classes and non-empty constructors. A few other options to consider are – custom serializers and mixins.
Hope that helps. Cheers,
Eugen.

Michael DeCourcey
Guest

Hello, In section 2 you describe the abstract type deserialization problem. The solution you provided works great if there is only one concrete type that you want to deserialize to, but usually when you use an interface or abstract class you have many concrete types that implement/extend that you would want to deserialize to.

In your example of Animal and Cat, is there a solution where you could deserialize to a Cat, Dog, or Horse?

Eugen Paraschiv
Guest

Hmm – that’s an interesting example to explore.
Yes, Jackson does have mechanism to deal with type erasure and the lack of type information at runtime.
Here’s what I’m thinking – can you reproduce the problem via a PR? Basically – introduce a parent with two children, and a failing test. I’ll merge that and then cover the scenario here.
Cheers,
Eugen.

Rajko Zagrajski
Guest

Hi,

Im trying to serialize/deserialize these two classes:

jackson throws an exception saying default constructor is needed forHandoverTreeNodeChlidren but it should use given constructor othewise nullpointer will be thrown. How do I tell it to use the constructor?

public class HandoverDefaultTreeNode implements TreeNode, Serializable {
@JsonDeserialize(contentAs = HandoverDefaultTreeNode.class)
@JsonManagedReference(“masterChild”)
private HandoverTreeNodeChlidren children;
@JsonBackReference(“masterChild”)
private TreeNode parent;
}

public class HandoverTreeNodeChlidren extends ArrayList {
public HandoverTreeNodeChlidren(TreeNode parent) {
this.parent = parent;

}
}

}

Eugen Paraschiv
Guest

Hey Rajko,
That’s an interesting question, but given that it involves this large code sample, let’s move the discussion over to an issue in Github.
Once it’s on Github, I’d be happy to have a look.
A final suggestion is a failing test that’s actually able to reproduce the problem on the module associated with this article – that’s going to help as well.
Cheers,
Eugen.

wpDiscuz