Com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: UnrecognizedPropertyException and unrecognized field
I am new to JSON and I am trying to apply the simplest JSON concept: https://github.com/FasterXML/jackson-databind
It's straightforward and very easy to follow. The explanation makes sense. POJO is clean and doesn't have a lot. The cartographer has to do the job, but it is not.
so I have the following code:
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
MyValue value = objectMapper.readValue("{\"name\":\"Bob\", \"age\":13}", MyValue.class);
System.out.println("- value.getName = ["+value.getName()+"] ");
System.out.println("- value.getAge = ["+value.getAge()+"] ");
} // main()
public class MyValue {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// Constructor
public MyValue() {
}
} // MyValue Class
when i run it it throws the following exception:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.csc.cloud.cp.service.solarwinds.orion.impl.SolarWindsOrionServiceImpl$MyValue]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: {"name":"Bob", "age":13}; line: 1, column: 2]
although I have my own default myValue () constructor.
So when I add the following annotation to the MyValue class:
// Constructor
@JsonCreator
public MyValue() {
}
I am getting the following exception
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "name" (class com.csc.cloud.cp.service.solarwinds.orion.impl.SolarWindsOrionServiceImpl), not marked as ignorable (0 known properties: ])
at [Source: {"name":"Bob", "age":13}; line: 1, column: 10] (through reference chain: com.csc.cloud.cp.service.solarwinds.orion.impl.SolarWindsOrionServiceImpl["name"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:51)
I pull my hair. Please, help!!!
thank
source to share
There are two possible solutions:
Decision
You can just add annotation @JsonIgnoreProperties(ignoreUnknown = true)
to your class MyValue
.
Solution two
Add to config objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
so that it objectMapper
doesn't work with unknown properties.
source to share