How To Solve Unrecognizedpropertyexception: Unrecognized Field, Non Marked Equally Ignorable - Json Parsing Mistake Using Jackson

Advertisement

Masukkan script iklan 970x90px

How To Solve Unrecognizedpropertyexception: Unrecognized Field, Non Marked Equally Ignorable - Json Parsing Mistake Using Jackson

Sabtu, 28 Maret 2020

While parsing JSON string received from i of our RESTful spider web services, I was getting this fault "Exception inwards thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized plain "person" (class Hello$Person), non marked equally ignorable". After exactly about research, I flora that this is i of the mutual fault spell parsing JSON document using Jackson opened upward source library inwards Java application. The fault messages state that it is non able to notice a suitable holding cite called "person" inwards our case, let's start have got a aspect at the JSON nosotros are trying to parse, the course of study nosotros are using to stand upward for the JSON document together with the fault message itself.

Error Message:
Exception inwards thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized plain "person" (class Hello$Person), non marked equally ignorable (4 known properties: , "id", "city", "name", "phone"])

The fault messages state that it tin notice out id, city, cite together with telephone attributes inwards the Person course of study but non able to locate the "person" field.

Our POJO course of study looks similar below:

class Person{
   private int id;
   private String name;
   private String city;
   private long phone;

   .....

}


together with the JSON String:
{
  "person": [
   {
     "id": "11",
     "name": "John",
     "city": "NewYork",
     "phone": 7647388372
   }
  ]
}

If yous aspect carefully, the "person" plain points to a JSON array together with non object, which agency it cannot live mapped to someone course of study directly.



How to solve this problem

Here are steps to solve this work together with acquire rid of this errorr:

1) Configure Jackson's ObjectMapper to non neglect when encounger unknown properties
You tin practise this yesteryear disabling DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES holding of ObjectMapper equally shown below:

// Jackson code to convert JSON String to Java object
ObjectMapper objectMapper = novel ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Person p = objectMapper.readValue(JSON, Person.class);

System.out.println(p);

Now, the fault volition acquire away but the Output is non what yous expected, it volition impress following:

Person [id=0, name=null, city=null, phone=0]

You tin reckon that Person course of study is non created properly, the relevant attributes are nil fifty-fifty though the JSON String contains its value.



The argue was that JSON String contains a JSON array, the someone plain is pointing towards an array together with at that spot is no plain corresponding to that inwards Person class.

In lodge to properly parse the JSON String nosotros involve to practise a wrapper course of study Community which volition have got an attribute to proceed an array of Person equally shown below:

static course of study Community {   individual List<Person> person;    world List<Person> getPerson() {     return person;   }    world void setPerson(List<Person> person) {     this.person = person;   }  }

Now, nosotros volition convert the JSON String to this Community course of study together with impress each someone from the listing equally shown below:

ObjectMapper objectMapper = novel ObjectMapper();
//objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Community c = objectMapper.readValue(JSON, Community.class);

for (Person p : c.getPerson()) {
   System.out.println(p);
}

This volition impress the details of a someone properly equally shown below:

Person [id=11, name=John, city=NewYork, phone=7647388372]

Now, coming dorsum to a to a greater extent than full general province of affairs where a novel plain is added on JSON but non available inwards your Person class, let's reckon what happens.

Suppose, our JSON String to parse is following:

{
"person": [
{
"id": "11",
"name": "John",
"city": "NewYork",
"phone": 7647388372,
"facebook": "JohnTheGreat"
}
]
}

When yous run the same computer program alongside this JSON String, yous volition acquire next error:

While parsing JSON string received from i of our RESTful spider web services How to Solve UnrecognizedPropertyException: Unrecognized field, non marked equally ignorable - JSON Parsing Error using Jackson


Again, Jackson is non able to recognize the novel "facebook" property. Now, nosotros tin ignore this holding yesteryear disabling the characteristic which tells Jackson to neglect on the unknown holding equally shown below:

ObjectMapper objectMapper = novel ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Community c = objectMapper.readValue(JSON, Community.class);

And this volition impress the someone course of study properly equally shown below:

Person [id=11, name=John, city=NewYork, phone=7647388372]

Alternatively, yous tin also role @JsonIgnoreProperties annotation to ignore undeclared properties.

The @JsonIgnoreProperties is a class-level annotation inwards Jackson together with it volition ignore every holding yous haven't defined inwards your POJO. Very useful when yous are exactly looking for a yoke of properties inwards the JSON together with don't desire to write the whole mapping.

This annotation provides command at course of study degree i.e. yous tin tell Jackson that for this class, delight ignore whatever attribute non defined yesteryear doing

@JsonIgnoreProperties(ignoreUnknown = true)

So, our Person course of study at nowadays looks like:

@JsonIgnoreProperties(ignoreUnknown = true)
static course of study Person{
private int id;
private String name;
private String city;
private long phone;

......

}


Sample program

import java.io.IOException; import java.util.List;  import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper;  /*  * {  "person": [  {  "id": "11",  "name": "John",  "city": "NewYork",  "phone": 7647388372  }  ]  }   */  public class Hello {    private static String JSON = "{\r\n" + " \"person\": [\r\n" + " {\r\n"       + " \"id\": \"11\",\r\n" + " \"name\": \"John\",\r\n"       + " \"city\": \"NewYork\",\r\n" + " \"phone\": 7647388372,\r\n"       + " \"facebook\": \"JohnTheGreat\"\r\n" + " }\r\n" + " ]\r\n" + " } ";    public static void main(String args[]) throws JsonParseException,       JsonMappingException, IOException {      ObjectMapper objectMapper = new ObjectMapper();     objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);     Community c = objectMapper.readValue(JSON, Community.class);      for (Person p : c.getPerson()) {       System.out.println(p);     }    }    static class Community {     private List<Person> person;      public List<Person> getPerson() {       return person;     }      public void setPerson(List<Person> person) {       this.person = person;     }    }    static class Person {     private int id;     private String name;     private String city;     private long phone;      public int getId() {       return id;     }      public void setId(int id) {       this.id = id;     }      public String getName() {       return name;     }      public void setName(String name) {       this.name = name;     }      public String getCity() {       return city;     }      public void setCity(String city) {       this.city = city;     }      public long getPhone() {       return phone;     }      public void setPhone(long phone) {       this.phone = phone;     }      @Override     public String toString() {       return "Person [id=" + id + ", name=" + cite + ", city=" + metropolis           + ", phone=" + telephone + "]";     }    } } 

When I run start version of this program, I was greeted alongside the next error:

Exception inwards thread "main" com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor flora for type [simple type, course of study Hello$Person]: tin non instantiate from JSON object (need to add/enable type information?)
at [Source: java.io.StringReader@5e329ba8; line: 2, column: 3]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:984)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:276)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at Hello.main(Hello.java:40)


This fault was occurring because my nested class Person was non static, which agency it cannot live instantiated because having whatever Outer course of study instance. The effect resolved subsequently making the Person class static.

If yous are non familiar alongside this item before, I propose yous cheque Java Fundamentals: The Core Platform, a costless course of study from Pluralsight to larn to a greater extent than most such details of Java programming language. You tin signup for a costless trial, which gives yous 10 days access, plenty to larn whole Java for free.

While parsing JSON string received from i of our RESTful spider web services How to Solve UnrecognizedPropertyException: Unrecognized field, non marked equally ignorable - JSON Parsing Error using Jackson



Now, let's reckon the existent error:

Exception inwards thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized plain "person" (class Hello$Person), non marked equally ignorable (4 known properties: , "id", "city", "name", "phone"])
at [Source: java.io.StringReader@4fbc9499; line: 2, column: 14] (through reference chain: Person["person"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:79)
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at Hello.main(Hello.java:40)

When yous run the lastly version of the computer program yous volition reckon next output:

Person [id=11, name=John, city=NewYork, phone=7647388372]

This agency nosotros are able to parse JSON containing unknown attributes successfully inwards Jackson.




How to compile together with run this program?

You tin only re-create glue the code into your favorite IDE e.g. Eclipse to compile together with run the program.

In Eclipse, yous don't fifty-fifty involve to practise the course of study file because it volition automatically practise the course of study together with bundle if yous re-create glue the code inwards Java project.

If Eclipse is your primary IDE together with yous desire to larn to a greater extent than of such productivity tips I propose yous cheque out The Eclipse Guided Tour - Part 1 together with ii By Tod Gentille.

While parsing JSON string received from i of our RESTful spider web services How to Solve UnrecognizedPropertyException: Unrecognized field, non marked equally ignorable - JSON Parsing Error using Jackson


It's a free, online course of study to larn both basic together with advanced characteristic of Eclipse IDE, which every Java developer should live aware of. You tin acquire access to this course of study yesteryear signing upward for a costless trial, which gives yous 10 days access to the whole Pluralsight library, i of the most valuable collection to larn most programming together with other technology. Btw, 10 days is to a greater extent than than plenty to larn Java together with Eclipse together.

Anyway, in i lawsuit yous re-create glue the code, all yous involve to practise is either include Maven dependency inwards your pom.xml or manually download required JAR file for Jackson opened upward source library.

For Maven Users
You tin add together next Maven dependency on your project's pom.xml together with and then run the mvn build or mvn install command to compile:


<dependency>   <groupId>com.fasterxml.jackson.core</groupId>   <artifactId>jackson-databind</artifactId>   <version>2.2.3</version> </dependency>

This dependency requires jackson-core together with jackson-annotations but Maven volition automatically download that for you.

Manually Downloading JAR
If yous are non using Maven or whatever other build tool e.g.gradle together with then yous tin exactly acquire to Maven key library together with download next 3 JAR files together with include them inwards your classpath:

jackson-databind-2.2.3.jar
jackson-core-2.2.3.jar
jackson-annotations-2.2.3.jar

Once yous compiled the course of study successfully yous tin run them equally yous run whatever other Java computer program inwards Eclipse, equally shown hither or yous tin run the JAR file using the command occupation equally shown here.

In short, The "com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized plain XXX, non marked equally ignorable" fault comes when yous endeavor to parse JSON to a Java object which doesn't comprise all the fields defined inwards JSON. You tin solve this fault yesteryear either disabling the characteristic of Jackson which tells it to neglect if come across unknown properties or yesteryear using annotation @JsonIgnoreProperties at the course of study level.

Further Learning
REST alongside Spring yesteryear Eugen Paraschiv
REST API Design, Development & Management
Java Web Fundamentals

Thanks for reading this article hence far. If yous similar my explanation together with then delight percentage alongside your friends together with colleagues. If yous have got whatever questions or feedback, delight driblet a  note.