Draaksward
Draaksward

Reputation: 811

Jackson serialize null or empty object

There is a POJO:

class A {
   private B b;
}

where B:

class B {
   private String c;
}

Is there a proper way of making Jackson serialize object of A, having A.b = null(or even b having all of it's fields as empty or default) in a form of:

{
   b: {}
}

And without the use of custom serializers. The upper POJO is actually complex, and maintaining the serializer will bring more trouble than benefit.

Upvotes: 0

Views: 1820

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38710

Set default property inclusionto to Include.NON_NULL:

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.IOException;

public class JsonApp {

  public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.setDefaultPropertyInclusion(Include.NON_NULL);

    System.out.println(mapper.writeValueAsString(new A()));
  }
}

class A {
  private B b = new B();

  public B getB() {
    return b;
  }

  public void setB(B b) {
    this.b = b;
  }
}

class B {
  private String c;

  public String getC() {
    return c;
  }

  public void setC(String c) {
    this.c = c;
  }
}

Above code prints:

{
  "b" : { }
}

Upvotes: 2

Related Questions