添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Ignoring null fields or attribute is a one of the common requirement while marshaling Java object to JSON string because Jackson just prints null when a reference filed is null , which you may not want. For example, if you have a Java object which has a String field whose value is null when you convert this object to Json, you will see null in front of that. In order to better control JSON output, you can ignore null fields , and Jackson provides a couple of options to do that. You can ignore null fields at the class level by using @JsonInclude(Include.NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null .
You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null. You can also ignore nulls at the object mapper level, e.g. by configuring it to ignore nulls globally .
I'll show you the example of each of these three ways to ignore null fields using Jackson, but before that let's first see an example of marshaling Java objects with null fields using Jackson to understand the problem better.
Btw, I expect that you know Java and are familiar with using third-party libraries like Jackson in your code. If you happen to just start with Java or want to refresh your Java knowledge, I suggest you first go through these free online Java courses to learn Javascratch. It's also the most up-to-date course and covers new features from recent Java versions.
public class JacksonTest {
  public static void main(String args[]) throws JsonProcessingException {
    // let's create a book with author as null
    Book cleanCode = new Book("Clean Code", null, 42);
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(cleanCode);
    System.out.println(json);
This will print the following output:
{"title":"Clean Code","author":null,"price":42}
You can see that the author is printed as null, which may not be ideal for many. This is still better than a NullPointerException but you could have been even better if the author field was not included in the output altogether.
 And, if that's precisely what you want, then you can ignore the fields with null values using @JsonInclude annotation in Jackson. Btw, if you are new to Jackson library then you can also check out this Jackson Quick Start: JSON Serialization with Java Made Easy course on Udemy. It's completely free and a good place to start Jackson basics.
Ignoring null fields at field level in Jackson Now, let's first see how we can ignore the fields with null values in JSON output at the field level. We can do this by annotating each field with @JsonInclude(Include.NON_NULL) annotation. If a field is annotated by this, then it will be not included in the JSON output if its null.
Here is an example to confirm this:
public class Book implements Comparable<Book> {
  private String title;
  @JsonInclude(Include.NON_NULL)
  private String author;
  private int price;
  public Book(String title, String author, int price) {
    this.title = title;
    this.author = author;
    this.price = price;
If you rerun the main method, this time it will produce a different output, I mean, without the author field as shown below:
{"title":"Clean Code","price":42}
But if you make the title null, then it will be the same issue as we have only ignored the author. So this solution makes sense to annotate all optional fields with @JsonInclude(Include.NON_NULL).
Btw, I am assuming here that you are familiar with JSON structure and JSON itself in general, If you are not, you can see this Introduction to JSON course on Udemy to understand the structure and properties of JSON.
Excluding null fields at class level Jackson also allows you to ignore null fields at the class level, which means every field which has a null value will be ignored. This is the same as annotating all fields with @JsonInclude(Include.NON_NULL) annotation.
So if you have a requirement where all the fields are optional or may contain null then instead of annotating every single field it's better to do it once at the class level as shown below:
@JsonInclude(Include.NON_NULL)
public class Book implements Comparable<Book> {
  private String title;
  private String author;
  private int price;
  public Book(String title, String author, int price) {
    this.title = title;
    this.author = author;
    this.price = price;
If you run the main class, we will again get the same JSON output as we got in the previous example, as shown below:
{"title":"Clean Code","price":42}
but if you make the title also null then you only get the price in the JSON output:
public class JacksonTest {
  public static void main(String args[]) throws JsonProcessingException {
    // let's create a book with author as null
    Book cleanCode = new Book(null, null, 42);
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(cleanCode);
    System.out.println(json);
Output:
{"price":42}
This happens because the Book class is annotated with @JsonInclude(Include.NON_NULL) which will exclude any null field. In this case, both the title and author were ignored.
You can see Jackson is a very popular and efficient Java library to map Java objects to JSON and vice-versa. If you want to learn the basics of the Jackson library and how to use them, I suggest you take a look at the Java: JSON Databinding with Jackson course on Pluralsight. One of the best courses to learn Jackson API for Java developers.
Ignoring null fields Globally You can also exclude null fields globally while converting Java objects to JSON by configuring this behavior on the ObjectMapper itself. This means all the classes will have this feature by themselves, and any field with null values will be ignored.
You can also configure ObjectMapper to ignore null fields globally by calling the setSerializationInclusion(Include.NON_NULL) method, as shown in the following example:
public class JacksonTest {
  public static void main(String args[]) throws JsonProcessingException {
    // let's create a book with author as null
    Book cleanCode = new Book(null, null, 42);
    ObjectMapper mapper = new ObjectMapper();
    // configure ObjectMapper to exclude null fields whiel serializing
    mapper.setSerializationInclusion(Include.NON_NULL);
    String json = mapper.writeValueAsString(cleanCode);
    System.out.println(json);
Output
{




    
"price":42}
This time also you get the same output even though you don't have @JsonInclude(Include.NON_NULL) at the top of your Book class because ObjectMapper will automatically ignore any field with a null value when this option is set.
That's all about how to ignore null fields while converting Java objects to JSON strings using Jackson. You have 3 ways to do it, ignore fields with null value at the field level, or class level, or globally at the ObjectMapper level. The rule of thumb is that you do it at field level for greater control and start with annotating the optional field which can be null.

Other JSON tutorials and courses you may like:
  • How to parse JSON using Gson? (tutorial)
  • 5 JSON parsing libraries Java Developers Should Know (libraries)
  • 10 Online courses to learn JavaScript in depth (courses)
  • How to parse a JSON array in Java? (tutorial)
  • Top 5 Courses to become full-stack Java developer (courses)
  • How to solve UnrecognizedPropertyException in Jackson? (solution)
  • 10 Advanced Core Java Courses for Experienced Developers (courses)
  • How to convert JSON to HashMap in Java? (guide) 10 Things Java developers should learn?  (article)
  • How to ignore unknown properties while parsing JSON in Java? (tutorial)
  • Top 5 Websites to learn Java For FREE (websites)
  • How to parse JSON with date fields in Java? (example)
  • 5 Courses to learn RESTful  API and Web services in Java? (courses)
  • 10 free courses to learn Java in-depth (resource)
  • Thanks for reading this article so far. If you like the Jackson JSON tutorial, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.
    P. S. - If are a complete beginner about JSON (JavaScript Object Notation) I strongly suggest you go through the Introduction to JSON course on Udemy to understand the structure and properties of JSON. This will help you a lot while dealing with JSON output, formating them, and producing them from your own API.
    1. you need to add this at the beginning:
      import com.fasterxml.jackson.annotation.JsonInclude;

      And also please note you will get an error if you just write:
      @JsonInclude(Include.NON_NULL)

      Instead use:
      @JsonInclude(JsonInclude.Include.NON_NULL)

      ReplyDelete
      Replies
      1. diff beween @JsonInclude(Include.NON_NULL) and @JsonInclude(JsonInclude.Include.NON_NULL)

        Delete
    2. if we are using same object for 2 endpoints - i want to not include certain fields in 1 endpoint, do not send these certain fields in another endpoint

      ReplyDelete
  • best JavaScript courses
  • best data structure and algorithms courses
  • Best Multithreading Courses
  • best MERN stack courses
  • Best Git courses
  • Best Microservice Courses
  • Best DevOps Courses
  • best MEAN stack Courses
  • free Java courses
  • free DSA courses
  • free sql courses
  • free Linux courses
  • Free Docker courses
  • free JUnit courses
  • Java 8 Stream filter() + findFirst Example Tutorial
  • Top 22 Array Concepts Interview Questions Answers ...
  • How to add and remove Elements from an Dynamic Arr...
  • How to Remove Objects From ArrayList while Iterati...
  • 9 JSP Implicit Objects and When to Use Them
  • How to implement PreOrder traversal of Binary Tree...
  • How to reverse a singly linked list in Java withou...
  • How to use Randam vs ThreadLocalRandom vs SecureRa...
  • How to implement Linear Search Algorithm in Java? ...
  • How to Convert String to LocalDateTime in Java 8 -...
  • How to use Stream.filter method in Java 8? Example...
  • How to reverse bits of an integer in Java? [LeetCo...
  • 10 Examples of Stream API in Java 8 - count + filt...
  • How to debug Java 8 Stream Pipeline - peek() metho...
  • Can you make an Abstract Class or Method Final in ...
  • How to Calculate Next Date and Year in Java | Loca...
  • How to Reverse an Array in place in Java? Example ...
  • 3 ways to ignore null fields while converting Java...
  • 5 Differences between an array and linked list in ...
  • What is difference between final vs finally and fi...
  • How to convert ArrayList to HashMap and LinkedHash...
  • How to code Binary Search Algorithm using Recursio...
  • Post Order Binary Tree Traversal in Java Without R...
  • 7 Examples to Sort One and Two Dimensional String ...
  • How to prepare Oracle Certified Master Java EE Ent...
  • How to use Record in Java? Example
  • How to Check is given String is a Palindrome in Ja...
  • Top 5 Free Apache Maven eBooks for Java Developers
  • Top 4 Free Microsoft SQL Server Books - PDF Downlo...
  • How to check if strings are rotations of each othe...
  • 4 Best Books to Learn Web Service in Java - SOAP a...
  • What is the cost of Oracle Java Certifications - O...
  • Top 3 Free Struts Books for Java EE developers - L...
  • Java Program to find Armstrong numbers with Example
  • Insertion Sort Algorithm in Java with Example
  • Difference between VARCHAR and NVARCHAR in SQL Server
  • How to Rotate an Array to Left or Right in Java? S...
  • How to implement Merge Sort Algorithm in Java [So...
  • What is Variable and Method Hiding in Java - Examp...
  • How to implement Comparator and Comparable in Java...
  • Difference between List <?> and List<Object> in J...
  • Java - Difference between getClass() and instanceo...
  • How to Read or Parse CSV files with Header in Java...
  • Java 8 StringJoiner Example - How to join multiple...
  • Can You Run Java Program Without a Main Method? [I...
  • How to Remove an Element from Array in Java with E...
  • How to remove duplicates from Collections or Strea...
  • How to Reverse String in Java with or without Stri...
  • What is double colon (::) operator in Java 8 - Exa...
  • How to copy Array in Java? Arrays copyOf and copyO...
  • How to Join Multiple Strings in Java 8 - String jo...
  • How to Find Nth Fibonacci Number in Java [Solved] ...
  • How to Find Square Root of a Number in Java [Solve...
  • How to implement Binary Tree PreOrder Traversal in...
  • Java 8 Stream map() function Example with Explanation
  • Top 21 Java HashMap Interview Questions and Answers
  • Top 15 Java 8 Stream and Functional Programming In...
  • Bubble sort in Java - Program to sort an Integer A...
  • How to Reverse an Integer in Java without converti...
  • How to implement linked list data structure in Jav...
  • 4 Examples to Round Floating-Point Numbers in Java...
  • Difference between Abstract class and Interface i...
  • How to Attach Apache Tomcat Server in Eclipse fo...
  • How to find difference between two dates in Java 8...
  • Top 5 Java 8 Default Methods Interview Questions a...
  • Spring Boot Interview questions
  • Spring Cloud Interview questions
  • Spring MVC Interview Questions
  • Microservices Interview questions
  • 10 Spring MVC annotations
  • Spring Boot Courses
  • Spring Framework Courses
  • Hibernate Interview Questions with Answers
  • System Design Interview Questions
  • Java Design Pattern Interview Questions with Answers
  • 40 Core Java Interview Questions with Answers
  • 10 Frequently asked SQL query Interview questions
  • 5 Free React.js Courses for Beginners
  • 5 Free Courses to learn Spring Boot and Spring MVC
  • 10 Free Java Courses for Beginners and Experienced
  • 10 Framework Java Developer Should Learn
  • 10 Books Java Programmers Should Read
  • 10 Open Source Libraries and Framework for Java Developers
  • 10 Programming language to Learn
  • 10 Books Every Programmer Should Read
  • 5 Great Books to Learn Java 8
  • 5 Free Database and SQL Query Courses for Beginners
  • 10 Free Data Structure and Algorithms Courses
  • Best Book to Learn Java for Beginners
  • 5 Books to Learn Spring MVC and Core Spring
  • 2 books to learn Hibernate for Java developers
  • 12 Advanced Java Programming Books for Experienced Programmers
  • 5 Free JavaScript Books to download
  • 5 Books to Improve Your Coding Skill
  • Books Every Programmer Should Read
  • Top 10 Computer Algorithm Books
  • 10 Free Java Programming Books
  • 5 Books to Learn Java 8 Better
  • Books Every Programmer Should Read
  • Top 10 Computer Algorithm Books
  •