6

I use Jackson, ObjectMapper.readValue(json, Class).

Have a class:

Component {
  private String name;
  private String someField;
  private boolean show = true; // if false -> skip it object
}

and extensible class:

ExtendedComponent extends Component {
  private List<Component> components = emptyList();// if all of object in list not showed -> skip field
}

and Complex class:

ComplexComponent extends Component {
      ExtendedComponent component;
    }

and json:

{
  "complexComponent": {
    "name": "complexName1",
    "show": true,
    "someField": "complex",
    "extendedComponent": {
      "components": [
        {
          "name": "someName1",
          "show": true,
          "someField": "someField"
        },
        {
          "name": "someName2",
          "show": false,
          "someField": "someField"
        },
        {
          "name": "someName3",
          "show": true,
          "someField": "someField"
        }
      ]
    }
  }
}

How to get objects only with name someName1 and someName3 in ExtendedComponent ?

And how to get nullable ComplexComponent if all of components is not showed?

  • check this [3. Skip Objects Conditionally](http://www.baeldung.com/jackson-serialize-field-custom-criteria) – Rcordoval Jun 02 '18 at 08:45
  • you can use `Boolean` instead of `boolean` and set it `null` in case of false (in setter method of this value). Now Just annotate that field with `@JsonInclude(Include.NON_NULL)` – Hemant Patel Jun 04 '18 at 08:36
  • Along a similar theme, you could create a new Enum with a single entry, for the positive/affirmative case. (that way you only end up with 2 permutations, either it is null or has a value. <-- this also works for cases where you don't have control over the setter (eg. autovalue builders) – CasualT Dec 18 '18 at 22:21

1 Answers1

10

Depending on your version of jackson 2

@JsonInclude(Include.NON_DEFAULT)

or

@JsonInclude(Include.NON_EMPTY)

should do the trick.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
TomWolk
  • 968
  • 10
  • 13