RSS 2.0
Sign In
# Thursday, August 6, 2015

We have solved this problem years ago, but have run into it once again.

So, we shall log the solution here.

The problem: to minify payload of the JAXB serialized beans.

Java beans have many properties most of them contains default values: zero ints, empty strings, and so on.

JAXB never tries to omit default value from marshalled xml, the only thing it can remove from output is null values. So, our approach is to define xml adapter to map default values to nulls.

Here we refer to the StackOverflow question: Prevent writing default attribute values JAXB, and to our answer.

Though it's not as terse as one would wish, one can create XmlAdapters to avoid marshalling the default values.

The use case is like this:

@XmlRootElement(name = "FIELD")
public class TestLayoutNode
  @XmlAttribute(name = "num")
  @XmlJavaTypeAdapter(value = IntegerZero.class, type = int.class)
  public int number;

  @XmlAttribute(name = "str")
  public String str = "default";

And here are adapters.


public class IntegerZero extends DefaultValue<Integer>
  public Integer defaultValue() { return 0; }


public class StringDefault extends DefaultValue<String>
  public String defaultValue() { return "default"; }


public class DefaultValue<T> extends XmlAdapter<T, T>
  public T defaultValue() { return null; }

  public T marshal(T value) throws Exception
    return (value == null) || value.equals(defaultValue()) ? null : value;

  public T unmarshal(T value) throws Exception
    return value;

With small number of different default values this approach works well.

Thursday, August 6, 2015 8:01:23 PM UTC  #    Comments [0] -
Java | Tips and tricks
Comments are closed.
<May 2024>
Total Posts: 387
This Year: 3
This Month: 0
This Week: 0
Comments: 1020
Locations of visitors to this page
The opinions expressed herein are our own personal opinions and do not represent our employer's view in anyway.

© 2024, Nesterovsky bros
All Content © 2024, Nesterovsky bros
DasBlog theme 'Business' created by Christoph De Baene (delarou)