Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

eBook – Jackson – NPI (cat=Jackson)
announcement - icon

Jackson and JSON in Java, finally learn with a coding-first approach:

>> Download the eBook

1. Overview

In this tutorial, we’ll go over the most common Jackson ExceptionsJsonMappingException,  UnrecognizedPropertyException, and MismatchedInputException.

Finally, we’ll briefly discuss Jackson “No such method” errors.

Further reading:

Jackson - Custom Serializer

Control your JSON output with Jackson 2 by using a Custom Serializer.

Jackson Annotation Examples

The core of Jackson is basically a set of annotations - make sure you understand these well.

Getting Started with Custom Deserialization in Jackson

Use Jackson to map custom JSON to any java entity graph with full control over the deserialization process.

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, which happens if the class is abstract or it is just an interface.

Here we’ll try to deserialize an instance from class Zoo that 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:

@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);
}

This is the full exception:

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. Solutions

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

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

Note that if we have more than one subtype of the abstract class, we should consider including subtype information as shown in the article Inheritance With Jackson.

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, JsonMappingException: No Suitable Constructor Found is thrown:

@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);
}

And this is the full exception:

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, we just add a default constructor:

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:

@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);
}

This is the full exception:

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:

@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 we try to serialize an instance while its properties and their getters are private.

We’ll try to serialize a UserWithPrivateFields:

public class UserWithPrivateFields {
    int id;
    String name;
}

When we try to serialize an instance of UserWithPrivateFields, JsonMappingException: No Serializer Found for Class is thrown:

@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);
}

And this is the full exception:

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:

@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 we can use the annotation @JsonAutoDetect:

@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 this 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);
}

And here’s the full exception:

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>:

@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. JsonMappingException: Cannot Deserialize Value of Type java.lang.String From Object Value

Before diving deep into the details, let’s try to understand what the exception means.

The stack trace of the exception says it all: “Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)“. It means that Jackson fails to deserialize an object into a String instance.

7.1. Reproducing the Exception

The most typical cause of this exception is mapping a JSON object into a String instance.

For instance, let’s consider the Person class:

public class Person {

    private String firstName;
    private String lastName;
    private String contact;

    // standard getters and setters
}

As shown above, we declared the contact field with the String type.

Now, let’s see what happens if we deserialize this JSON string:

{
    "firstName":"Azhrioun",
    "lastName":"Abderrahim",
    "contact":{
        "email":"[email protected]"
    }
}

Jackson fails with the stack trace:

Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (String)"{"firstName":"Azhrioun","lastName":"Abderrahim","contact":{"email":"[email protected]"}}"; line: 1, column: 59] (through reference chain: com.baeldung.exceptions.Person["contact"])
...

Let’s confirm this using a test case:

@Test
public void givenJsonObject_whenDeserializingIntoString_thenException() throws IOException {
    final String json = "{\"firstName\":\"Azhrioun\",\"lastName\":\"Abderrahim\",\"contact\":{\"email\":\"[email protected]\"}}";
    final ObjectMapper mapper = new ObjectMapper();

    Exception exception = assertThrows(JsonMappingException.class, () -> mapper.reader()
      .forType(Person.class)
      .readValue(json));

    assertTrue(exception.getMessage()
      .contains("Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)"));
}

As we can see, we tried to deserialize the JSON object: “contact”:{“email”: “[email protected]”}}” into the contact property which is String. Hence the exception.

7.2. The Solution

The easiest solution would be mapping every JSON object to a Java object and not to a simple String object.

So, let’s create another class Contact to denote the JSON object“contact”:{“email”: “[email protected]”}}”:

public class Contact {

    private String email;

    // standard getter and setter
}

Next, let’s rewrite the Person class to change the contact type from String to Contact:

public class PersonContact {

    private String firstName;
    private String lastName;
    private Contact contact;
 
    // standard getters and setters
}

Now, we’re going to add another test case to verify that everything works as excepted:

@Test
public void givenJsonObject_whenDeserializingIntoObject_thenDeserialize() throws IOException {
    final String json = "{\"firstName\":\"Azhrioun\",\"lastName\":\"Abderrahim\",\"contact\":{\"email\":\"[email protected]\"}}";
    final ObjectMapper mapper = new ObjectMapper();

    PersonContact person = mapper.reader()
      .forType(PersonContact.class)
      .readValue(json);

    assertEquals("[email protected]", person.getContact().getEmail());
}

8. UnrecognizedPropertyException

8.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.

We’ll 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);
}

This is the full exception:

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)

8.2. The Solution

We can solve this problem by configuring the ObjectMapper:

@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 {...}

9. JsonParseException: Unexpected Character (”’ (code 39))

9.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.

We’ll 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);
}

Here’s the full exception:

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)

9.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);
}

10. JsonParseException: Unexpected Character (‘c’ (code n))

In this section, we’ll address another common parsing exception, JsonParseException: Unexpected character (‘c’ (code n)). This exception occurs when the JSON parser encounters an unexpected character during the parsing process. The specific unexpected character (‘c’) and its Unicode codepoint (‘n’) are indicated in the exception message.

10.1. The Problem

The JsonParseException: Unexpected character (‘c’ (code n)) exception typically arises due to syntax errors or invalid characters within the JSON string being parsed. These errors can result from various issues such as missing commas, incorrect nesting of JSON objects or arrays, or the presence of characters that are not allowed in JSON syntax.

Let’s try to deserialize a JSON string that contains missing double quotes around the ‘name’ field:

@Test(expected = JsonParseException.class)
public void givenInvalidJsonString_whenDeserializing_thenException() throws JsonProcessingException, IOException {
    String json = "{\"id\":1, name:\"John\"}"; // Missing double quotes around 'name'
    ObjectMapper mapper = new ObjectMapper();
    mapper.reader().forType(User.class).readValue(json);
}

Here’s the full exception:

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('n' (code 110)): 
was expecting double-quote to start field name
at [Source: (String)"{"id":1, name:"John"}"; line: 1, column: 11]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:2477)

10.2. The Solution

To address the JsonParseException: Unexpected character (‘c’ (code n)) exception, it’s crucial to carefully review the JSON string for syntax errors and ensure that it adheres to the JSON specification.

Common solutions include correcting syntax errors such as missing or misplaced commas, ensuring proper nesting of objects and arrays, and removing any characters that are not allowed in JSON syntax.

11. MismatchedInputException: Cannot Deserialize Instance

The MismatchedInputException exception has different variants. It can occur when we do not provide a default constructor for a POJO class or do not annotate constructor parameters for immutable fields with @JsonProperty.

Also, the exception can occur if we deserialize an incompatible JSON array into a Java object.

11.1. The Problem: No Default Constructor

This exception occurs when trying to deserialize a JSON string into a POJO class without a default or no-arg constructor. Since Jackson needs to instantiate the target class, not having a default constructor will result in an exception.

To demonstrate the exception, let’s create a class named Book:

class Book {
    private int id;
    private String title;  
    
    public Book(int id, String title) {
        this.id = id;
        this.title = title; 
    }  
    // getters and setters
}

Here, we create a POJO class without the default constructor.

Next, let’s map a JSON string to the POJO class:

@Test
void givenJsonString_whenDeserializingToBook_thenIdIsCorrect() throws JsonProcessingException {
    String jsonString = "{\"id\":\"10\",\"title\":\"Harry Potter\"}";
    ObjectMapper mapper = new ObjectMapper();
    Book book = mapper.readValue(jsonString, Book.class);
    assertEquals(book.getId(),10);
}

The above test throws a MismatchedInputException:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 
Cannot construct instance of `com.baeldung.mismatchedinputexception.Book` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"id":"10","title":"Harry Potter"}"; line: 1, column: 2]

11.2. The Solution

Let’s solve this problem by adding the default constructor to the Book class:

// ...   
public Book() {
}
// ...

The test that produces the error now passes with the introduction of the default constructor.

11.3. The Problem: Missing @JsonProperty Annotation

A POJO class that has a field marked as final cannot have a default constructor if the field isn’t initialized at the time of its declaration. This is because the final field must be set via the constructor or directly at the declaration.

Since there’s no default constructor, deserializing JSON into a class instance fails with MismachedInputException.

Let’s create a POJO class named Animal with an immutable field:

class Animals {
    private final int id;
    private String name;
    
    public Animals(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

Then, let’s map a JSON string to the POJO class:

@Test
void givenJsonString_whenDeserializingToJavaObjectWithImmutableField_thenIdIsCorrect() throws JsonProcessingException {
    String jsonString = "{\"id\":10,\"name\":\"Dog\"}";
    ObjectMapper mapper = new ObjectMapper();
    Animals animal = mapper.readValue(jsonString, Animals.class);
    assertEquals(animal.getId(),10);
}

Here, we assert that the id is equal to an expected id. However, this throws an exception:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 
Cannot construct instance of `com.baeldung.mismatchedinputexception.Animals` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"id":10,"name":"Dog"}"; line: 1, column: 2]

11.4. Solution

We can solve this problem by annotating the parameters with @JsonProperty:

Animals(@JsonProperty("id") int id, @JsonProperty("name") String name) {
   this.id = id;
   this.name = name;
}

11.5. The Problem: Incompatible Java Object

Additionally, this error also occurs when Jackson tries to deserialize a JSON array into a Java object that’s incompatible.

To stage this error, let’s use the Book class we created earlier and pass the JSON array into a single Book object:

@Test
void givenJsonString_whenDeserializingToBookList_thenTitleIsCorrect() throws JsonProcessingException {
    String jsonString = "[{\"id\":\"10\",\"title\":\"Harry Potter\"}]";
    ObjectMapper mapper = new ObjectMapper();
    Book book = mapper.readValue(jsonString, Book.class);
    assertEquals(book.getTitle(),"Harry Potter");
}

In the code above, we map a JSON array to a single object. This throws an exception:

com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Cannot deserialize value of type `com.baeldung.mismatchedinputexception.Book` from Array value (token `JsonToken.START_ARRAY`)
at [Source: (String)"[{"id":"10","title":"Harry Potter"}]"; line: 1, column: 1]

11.6. The Solution

Let’s solve this problem by deserializing the JSON array in a List object:

@Test
void givenJsonString_whenDeserializingToBookList_thenTitleIsCorrect() throws JsonProcessingException {
    String jsonString = "[{\"id\":\"10\",\"title\":\"Harry Potter\"}]";
    ObjectMapper mapper = new ObjectMapper();
    List<Book> book = mapper.readValue(jsonString, new TypeReference<List<Book>>(){});
    assertEquals(book.get(0).getTitle(),"Harry Potter");
}

However, our intention may be to deserialize a single JSON string instead of a JSON array. We can remove the square bracket from the jsonString and map it to a single Java object.

12. Jackson NoSuchMethodError

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

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

This is the full exception:

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

13. Conclusion

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

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)