开发者

How to avoid serializing zero values with Simple Xml

开发者 https://www.devze.com 2023-03-25 06:27 出处:网络
I\'m trying to serialise an object using simple xml (http://simple.sourceforge.net/). The object setup is pretty simple:

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:

开发者_StackOverflow社区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?


The 'problem' here is your using primitive types (int, char, byte, ...).

In Java you can use primitive wrapper objects (Integer, Chat, Byte) instead so they'll be treated like any other object and can be null. Thanks to autoboxing you can assign primitives to their object variant.

So I suggest changing you model like following:

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

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

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

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

And magic! The node has disappeared! ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号