JsonMappingException No suitable constructor found
If you are using Jackson API to convert Java to JSON vice versa and get below exception:
Exception in thread “main” com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.javahonk.Peoples]: can not instantiate from JSON object (need to add/enable type information?) at [Source: {"firstName":"tset","lastName":"lastName","age":15}; line: 1, column: 2] at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1071) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:264) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:124) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3066) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2161) at com.javahonk.JsonConversionUsingJackson.main(JsonConversionUsingJackson.java:19)
- Solution: You will get this exception if default constructor is missing from java class while converting json object to java object. Please include default constructor in the class. As as example below Peoples class shows default constructor:
Peoples.java:
public class Peoples { private String firstName; private String lastName; private int age; public Peoples(){} public Peoples(String firstName, String lastName, int age) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Peoples [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]"; } }
For more information please read Jackson documentation here