How to avoid serializing zero values with Simple Xml

Posted by Bram Vandenbussche on Stack Overflow See other posts from Stack Overflow or by Bram Vandenbussche
Published on 2011-08-03T19:37:43Z Indexed on 2012/11/01 23:01 UTC
Read the original article Hit count: 380

I'm trying to serialise an object using simple xml (http://simple.sourceforge.net/). The object setup is pretty simple:

@Root(name = "order_history")
public class OrderHistory {

    @Element(name = "id", required = false)
    public int ID;

    @Element(name = "id_order_state")
    public int StateID;

    @Element(name = "id_order")
    public int OrderID;
}

The problem is when I create a new instance of this class without an ID:

OrderHistory newhistory = new OrderHistory();
newhistory.OrderID = _orderid;
newhistory.StateID = _stateid;

and I serialize it via simple xml:

StringWriter xml = new StringWriter();
Serializer serializer = new Persister();
serializer.write(newhistory, xml);

it still reads 0 in the resulting xml:

<?xml version='1.0' encoding='UTF-8'?>
<order_history>
    <id>0</id>
    <id_order>2</id_order>
    <id_order_state>8</id_order_state>
</order_history>

I'm guessing the reason for this is that the ID property is not null, since integers can't be null. But I really need to get rid of this node, and I'd rather not remove it manually.

Any clues anyone?

© Stack Overflow or respective owner

Related posts about java

Related posts about serialization