Annotation to Ignore Unmappable Fields When Reading
1 of the common problems while parsing JSON in Coffee using Jackson API is that information technology fails when your JSON contains unknown properties i.due east. your Java grade doesn't have all the fields corresponding to all JSON properties. For example, if you lot are consuming JSON from a Remainder Web Service and tomorrow they added a new field into JSON then your code will break because Jackson will throw UnrecognizedPropertyException and stop parsing JSON. This is troublesome and can cause issues in production if you lot are not aware. I have faced this issue when a developer shipped the code to consume data from REST API without properly handling unknown fields.
The lawmaking worked fine for months but it broke as soon as the source arrangement added a new field is added to REST API. The developer chooses to ignore the update because nosotros weren't interested in that field just he failed to foresee that it will impact the JSON parsing.
Anyway, it was our error that we didn't review the lawmaking properly and allowed him to release his lawmaking into product without handling unknown files. The upshot could take only been avoided if he was familiar with Jackson library in a petty scrap more detail.
Jackson API provides 2 ways to ignore unknown fields, first at the form level using @JsonIgnoreProperties annotation and second at the ObjectMapper level using configure() method.
You will see both approaches in this article and learn how to employ them and when to use @JsonIgnoreProperties and when to ignore unknown fields in JSON globally at the ObjectMapper level.
Btw, if you are learning Coffee then I propose you offset go through these costless Java online courses to build the foundation.
Ignoring unknown properties using @JsonIgnoreProperties
If y'all are creating a Model course to stand for the JSON in Java, then you can annotate the class with @JsonIgnoreProperties(ignoreUnknown = true) to ignore whatever unknown field. This means if there is a new field is added tomorrow on JSON which represents your Model then Jackson will not throw UnrecognizedPropertyException while parsing JSON in Coffee.
You tin use this arroyo if you desire to ignore unknown backdrop only for that Model class, only this is the preferred approach because it provides you more control.
Let'due south run into an example of using @JsonIgnoreProperties in Java:
Suppose I accept the following JSON, which represents my favorite book, Effective Java tertiary Edition, a must-read book for every Java programmer, and a Java model course in my project:
If tomorrow, I add a new field called "edition" in the JSON then parsing of this JSON will neglect with the UnrecognizedPropertyException error. Something like :
Exception in thread "chief" com.fasterxml .jackson .databind .exc .UnrecognizedPropertyException: Unrecognized field "edition" (grade EBook), not marked equally ignorable (three known backdrop: , "title", "price", "author"])" This means Jackson is not able to notice any field in your EBook course for the "edition" property in JSON and hence information technology's throwing the UnrecognizedPropertyException error.
You can solve this problem and forestall this error by using @JsonIgnoreProperties notation as shown beneath:
@JsonIgnoreProperties(ignoreUnknown = truthful) grade EBook{ private String title; private String author; private int price; .. }
We have only annotated a whole model class as @JsonIgnoreProperties(ignoreUnknown = true), which mean any unknown belongings in JSON Cord i.east. any holding for which we don't have a corresponding field in the EBook class will be ignored. If you compile and run your programme again information technology will work fine.
In Jackson 2.10, the @JsonIgnoreProperties reside in com.fasterxml.jackson.annotation parcel, hence you need to import it as :
import com.fasterxml .jackson .annotation .JsonIgnoreProperties. If you are using an older version of Jackson API e.g. Jackson 1.x then this annotation belongs to a different package, beware of that, specially if y'all take both Jackson 1.x and Jackson 2.ten in your classpath.
Ignoring Unknown Belongings in JSON Globally using Jackson
Another fashion to bargain with unknown properties in JSON y'all are parsing is to configure ObjectMapper not to neglect when it encounters an unknown property. This will also solve the trouble of UnrecognizedPropertyException. Y'all can enable this setting by calling configure() method every bit shown below:
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
This will now ignore unknown properties for any JSON it'south going to parse, You should just use this option if you lot can't annotate a class with @JsonIgnoreProperties annotation.
Btw, if y'all are not familiar with JSON parsing libraries in Coffee, then JSON with Java APIs, jQuery, and Residual Web Services on Udemy is a good place to start with.
Java Program to Ignore Unknown Properties while Parsing JSON using Jackson
Allow'due south see whatever we have learned so far in activeness. Btw, if y'all are dislocated with my Cord JSON and a lot of "/r/n" cord then don't worry. I haven't done that manually. I used this Eclipse flim-flam to re-create my JSON and it automatically included necessary escape characters. This is required because JSON string is enclosed with double quotes ("") which demand to be escaped in Coffee.
Btw, if you are new to Eclipse IDE, then I propose you check Beginners Eclipse Java IDE Grooming Course on Udemy to larn it well. It'southward important for Java developer to know their tools well, especially IDE and so that they effectively develop, examination, debug, and run their Coffee application.
import java.io.IOException; import coffee.text.SimpleDateFormat; import java.util.Appointment; import com.fasterxml.jackson.cadre.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; /* * Java Plan to iterate over JSONObject of json-elementary */ public class JacksonTest { individual static String json = "{\r\n" + "\"championship\" : \"Effective Java\",\r\n" + "\"writer\" : \"Joshua Bloch\",\r\n" + "\"price\" : 37,\r\n" + "\"edition\" : 37\r\northward" + "}"; public static void primary(String args[]) throws IOException { // allow's parse JSON with a date field ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, // simulated); EBook effectiveJava = mapper.readValue(json, EBook.grade); System.out.println("Input json string"); System.out.println(json); Organization.out.println("Generated java course: "); System.out.println(effectiveJava); } } grade EBook { private String title; private String writer; private int price; public EBook() { // no argument constructor required by Jackson } public EBook(String title, String author, int price) { this.title = title; this.writer = writer; this.price = price; } public String getTitle() { return title; } public String getAuthor() { return author; } public int getPrice() { render price; } public void setTitle(String title) { this.championship = title; } public void setAuthor(Cord author) { this.author = author; } public void setPrice(int price) { this.price = price; } @Override public Cord toString() { return "EBook [title=" + title + ", author=" + author + ", price=" + price + "]"; } } Output: Input json string { "championship" : "Effective Java", "author" : "Joshua Bloch", "price" : 37, "version" : 37 } Generated java form: EBook [title =Effective Java, author=Joshua Bloch, price= 37]
In this program, I have a JSON equally discussed above which represents the Effective Coffee 3rd edition book, a must-read for every Java programmer.
I as well have a model course called EBook, which is annotated with @JsonIgnoreProperties(ignoreUnknown = true) to ignore unknown backdrop.
If y'all look closely, our JSON Cord contains an "edition" property that is not defined in the Java class only the program works because nosotros take marked EBook with
@JsonIgnoreProperties(ignoreUnknown = true) notation.
If you want to examination this program, then just remove that annotation and run the program, it will throw the following error.
Exception in thread "main" com.fasterxml.jackson.databind.exc .UnrecognizedPropertyException: Unrecognized field "edition" (class EBook), not marked every bit ignorable (three known properties : , "title", "price", "author"]) at [Source: java.io.StringReader@19dfb72a; line: 5, column: 14] (through reference chain: EBook["edition"]) at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException .from(UnrecognizedPropertyException.java: 79) at com.fasterxml.jackson.databind.DeserializationContext .reportUnknownProperty(DeserializationContext.coffee: 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 JacksonTest.principal(JacksonTest.java: 30) This happened because of the "edition" field which is only present in JSON and not in the Java class. If you put the annotation back and so the lawmaking will piece of work again.
Yous can similarly test how to ignore unknown fields at the object mapper level, instead of putting the @JsonIgnoreProperties notation back, you but uncomment the mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) line in the code and run the program. This time as well information technology will piece of work considering Jackson is ignoring all unknown properties.
That'south all about how to ignore unknown properties while parsing JSON in Java using Jackson API. You lot can do this either by using @JsonIgnoreProperties annotation or configuring ObjectMapper to not fail when encountering unknown properties during deserialization past disablingFAIL_ON_UNKNOWN_PROPERTIES.
Though, the preferred approach is to ignore unknown properties at the class level using @JsonIgnoreProperties(ignoreUnknown = true) and only practice this on the ObjectMapper level if you can't annotate your class with this notation i.due east. you don't ain the grade. It's also a all-time practice to annotated your model class with @JsonIgnoreProperties to avoid the issue I have explained in the first paragraph.
Other Java and JSON resources you may similar
How to parse JSON using Gson?
5 JSON parsing libraries Java Developers Should Know
How to parse JSON assortment in Java?
How to convert JSON to HashMap in Java?
10 Things Java developers should learn
Thanks for reading this article so far. If you lot similar this article then please share it with your friends and colleagues. If y'all have whatever questions or doubts, delight drib a note.
Source: https://javarevisited.blogspot.com/2018/01/how-to-ignore-unknown-properties-parsing-json-java-jackson.html
0 Response to "Annotation to Ignore Unmappable Fields When Reading"
Post a Comment