478

I am getting the following error when trying to get a JSON request and process it:

org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.myweb.ApplesDO]: can not instantiate from JSON object (need to add/enable type information?)

Here is the JSON I am trying to send:

{
  "applesDO" : [
    {
      "apple" : "Green Apple"
    },
    {
      "apple" : "Red Apple"
    }
  ]
}

In Controller, I have the following method signature:

@RequestMapping("showApples.do")
public String getApples(@RequestBody final AllApplesDO applesRequest){
    // Method Code
}

AllApplesDO is a wrapper of ApplesDO :

public class AllApplesDO {

    private List<ApplesDO> applesDO;

    public List<ApplesDO> getApplesDO() {
        return applesDO;
    }

    public void setApplesDO(List<ApplesDO> applesDO) {
        this.applesDO = applesDO;
    }
}

ApplesDO:

public class ApplesDO {

    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String appl) {
        this.apple = apple;
    }

    public ApplesDO(CustomType custom){
        //constructor Code
    }
}

I think that Jackson is unable to convert JSON into Java objects for subclasses. Please help with the configuration parameters for Jackson to convert JSON into Java Objects. I am using Spring Framework.

EDIT: Included the major bug that is causing this problem in the above sample class - Please look accepted answer for solution.

2
  • 2
    I don't see any subclasses in the above code, is this code what your trying or are you making up a simpler example?
    – gkamal
    Commented Oct 2, 2011 at 12:35
  • I added an answer with some more explanation of how it works. Basically, you need to realize Java doesn't keep method argument names in runtime.
    – Vlasec
    Commented Aug 9, 2016 at 10:16

14 Answers 14

610

So, finally I realized what the problem is. It is not a Jackson configuration issue as I doubted.

Actually the problem was in ApplesDO Class:

public class ApplesDO {

    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String apple) {
        this.apple = apple;
    }

    public ApplesDO(CustomType custom) {
        //constructor Code
    }
}

There was a custom constructor defined for the class making it the default constructor. Introducing a dummy constructor has made the error to go away:

public class ApplesDO {

    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String apple) {
        this.apple = apple;
    }

    public ApplesDO(CustomType custom) {
        //constructor Code
    }

    //Introducing the dummy constructor
    public ApplesDO() {
    }

}
11
  • May I ask where CustomType comes from. I am trying a structure like this but I am absolutely new to Java.
    – andho
    Commented Jan 11, 2013 at 9:19
  • 187
    You can use jackson with inner (nested) classes, serialization works just fine in this case. The only stumbling block is that the inner class must be marked as "static" for deserialization to work properly. See exlanation here: cowtowncoder.com/blog/archives/2010/08/entry_411.html
    – jpennell
    Commented Feb 14, 2013 at 1:35
  • 3
    Could someone please explain why this happens? I had a very similar error. Thought all the right constructors were in place, but could not deserialize. It only worked after I added a dummy constructor, after reading this post. Commented Apr 28, 2014 at 14:59
  • 7
    @Suman I would not call this a dummy constructor - it's just the default constructor. Not only is it perfectly valid, but is required for many kinds of java bean-type processing. (And, of course, it tripped me up. :-) )
    – fool4jesus
    Commented Apr 20, 2015 at 19:26
  • 2
    If you don't want to add default constructor (e.g., when you are dealing with immutable objects). You will have to tell which constructor or factory method to use to instantiate the object using JsonCreator annotation.
    – Rahul
    Commented Mar 14, 2016 at 14:21
393

This happens for these reasons:

  1. your inner class should be defined as static

    private static class Condition {  //jackson specific    
    }
    
  2. It might be that you got no default constructor in your class (UPDATE: This seems not to be the case)

    private static class Condition {
        private Long id;
    
        public Condition() {
        }
    
        // Setters and Getters
    }
    
  3. It could be your Setters are not defined properly or are not visible (e.g. private setter)

10
  • 101
    static class made the difference in my case. Thanks!
    – jalogar
    Commented Nov 20, 2014 at 10:12
  • 3
    And of course, you don't need to declare an empty, no-argument default constructor, Java does it for you! (As long as you don't define any other constructors.)
    – Jonik
    Commented Feb 4, 2015 at 13:21
  • 1
    @Jonik, right! my answer is old, if I remember correct, since Jackson is using reflection to get to the inner class, I guess it was needed to define the default constructor(could be also not a case in newer versions), but since I'm not sure you could be correct.
    – azerafati
    Commented Feb 4, 2015 at 14:37
  • 6
    Yeah, my experience is with Jackson 2.4.4: indeed Java's implicit default constructor is enough. You need to explicitly write the no-args constructor only if you've defined other constructors that do take arguments (i.e. when Java does not generate the no-args one for you).
    – Jonik
    Commented Feb 10, 2015 at 16:57
  • 1
    I logged in so that I can say thank you, making my inner classes static solved the problem Commented Oct 27, 2015 at 20:49
59

I would like to add another solution to this that does not require a dummy constructor. Since dummy constructors are a bit messy and subsequently confusing. We can provide a safe constructor and by annotating the constructor arguments we allow jackson to determine the mapping between constructor parameter and field.

so the following will also work. Note the string inside the annotation must match the field name.

import com.fasterxml.jackson.annotation.JsonProperty;
public class ApplesDO {

        private String apple;

        public String getApple() {
            return apple;
        }

        public void setApple(String apple) {
            this.apple = apple;
        }

        public ApplesDO(CustomType custom){
            //constructor Code
        }

        public ApplesDO(@JsonProperty("apple")String apple) {
        }

}
5
  • This solution did the trick. I just want to mention the following, I had a constructor, but the name of the parameters was different than that of the instance-parameters, so it couldn't be mapped. Adding the annotation solved it, but renaming the parameters would have probably worked also.
    – Fico
    Commented Jul 23, 2015 at 7:47
  • What if the constructor parameter is not in the response? Can it be injected another way? Commented Nov 25, 2015 at 4:52
  • The only significant data that is being sent here is the String apple that is the response.
    – PiersyP
    Commented Nov 25, 2015 at 12:25
  • 1
    This was useful to me because I wanted my object to be immutable, so a dummy constructor was not an option. Commented Apr 7, 2016 at 16:38
  • In my case it also requires to add @JsonCreator on the constructor with @JsonProperty.
    – m1ld
    Commented Apr 27, 2016 at 12:08
30

When I ran into this problem, it was a result of trying to use an inner class to serve as the DO. Construction of the inner class (silently) required an instance of the enclosing class -- which wasn't available to Jackson.

In this case, moving the inner class to its own .java file fixed the problem.

1
  • 7
    Whereas moving the inner class to its own .java file works, adding the static modifier also addresses the problem as mentioned in @bludream's answer.
    – jmarks
    Commented Feb 15, 2016 at 21:56
25

Generally, this error comes because we don’t make default constructor.
But in my case:
The issue was coming only due to I have made used object class inside parent class.
This has wasted my whole day.

2
  • 4
    It's enough to make the nested class static.
    – sloth
    Commented Sep 9, 2019 at 12:47
  • making it static worked for me. Thanks @sloth Commented Dec 8, 2020 at 17:20
13

Thumb Rule: Add a default constructor for each class you used as a mapping class. You missed this and issue arise!
Simply add default constructor and it should work.

0
10

Can you please test this structure. If I remember correct you can use it this way:

{
    "applesRequest": {
        "applesDO": [
            {
                "apple": "Green Apple"
            },
            {
                "apple": "Red Apple"
            }
        ]
    }
}

Second, please add default constructor to each class it also might help.

3
  • Not working: Getting following error: "org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field &quot;applesRequest&quot; (Class com.smartshop.dao.AllApplesDO), not marked as ignorable" Commented Oct 2, 2011 at 10:54
  • Previously it used to at least not through error for AllApplesDO and throws only for enclosed class.. now it throws for the first class itself Commented Oct 2, 2011 at 10:54
  • shouldn't this be chosen as the CORRECT answer?
    – fast tooth
    Commented Aug 24, 2016 at 18:02
8

You have to create dummy empty constructor in our model class.So while mapping json, it set by setter method.

2
  • This is the fix. Commented Feb 19, 2020 at 19:30
  • That's also the case for me. I had many different constructors for my object, and so I just created another empty one that apparently gets used by jackson. Commented Apr 10, 2020 at 10:03
6

Regarding the last publication I had the same problem where using Lombok 1.18.* generated the problem.

My solution was to add @NoArgsConstructor (constructor without parameters), since @Data includes by default @RequiredArgsConstructor (Constructor with parameters).

lombok Documentation https://projectlombok.org/features/all

That would solve the problem:

package example.counter;

import javax.validation.constraints.NotNull;

import lombok.Data;

@Data
@NoArgsConstructor
public class CounterRequest {
    @NotNull
    private final Integer int1;

    @NotNull
    private final Integer int2;
}
5

If you start annotating constructor, you must annotate all fields.

Notice, my Staff.name field is mapped to "ANOTHER_NAME" in JSON string.

     String jsonInString="{\"ANOTHER_NAME\":\"John\",\"age\":\"17\"}";
     ObjectMapper mapper = new ObjectMapper();
     Staff obj = mapper.readValue(jsonInString, Staff.class);
     // print to screen

     public static class Staff {
       public String name;
       public Integer age;
       public Staff() {         
       }        

       //@JsonCreator - don't need this
       public Staff(@JsonProperty("ANOTHER_NAME") String   n,@JsonProperty("age") Integer a) {
        name=n;age=a;
       }        
    }
5

You must realize what options Jackson has available for deserialization. In Java, method argument names are not present in the compiled code. That's why Jackson can't generally use constructors to create a well-defined object with everything already set.

So, if there is an empty constructor and there are also setters, it uses the empty constructor and setters. If there are no setters, some dark magic (reflections) is used to do it.

If you want to use a constructor with Jackson, you must use the annotations as mentioned by @PiersyP in his answer. You can also use a builder pattern. If you encounter some exceptions, good luck. Error handling in Jackson sucks big time, it's hard to understand that gibberish in error messages.

2
  • The reason you need a "default no argument constructor" FooClass() is likely because Spring follows the JavaBean Specification, which requires this to work for automatically marshalling and unmarshalling when serializing and deserializing objects.
    – atom88
    Commented Oct 20, 2017 at 17:18
  • Well, Java serialization and deserialization into binary stream is not what the question is about, anyway. So it is only good that Jackson offers multiple patterns to be used with deserialization. I especially like the builder pattern as it allows the resulting object to be immutable.
    – Vlasec
    Commented Oct 23, 2017 at 10:41
1

Add default constructors to all the entity classes

0

Failing custom jackson Serializers/Deserializers could also be the problem. Though it's not your case, it's worth mentioning.

I faced the same exception and that was the case.

0

For me, this used to work, but upgrading libraries caused this issue to appear. Problem was having a class like this:

package example.counter;

import javax.validation.constraints.NotNull;

import lombok.Data;

@Data
public class CounterRequest {
    @NotNull
    private final Integer int1;

    @NotNull
    private final Integer int2;
}

Using lombok:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.0</version>
</dependency>

Falling back to

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.10</version>
</dependency>

Fixed the issue. Not sure why, but wanted to document it for future.

Not the answer you're looking for? Browse other questions tagged or ask your own question.