如何避免使用 Simple Xml 序列化零值
我正在尝试使用简单的 xml (http://simple.sourceforge.net/) 序列化一个对象。对象设置非常简单:
@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;
}
问题是当我创建一个没有 ID 的类的新实例时:
OrderHistory newhistory = new OrderHistory();
newhistory.OrderID = _orderid;
newhistory.StateID = _stateid;
并且我通过简单的 xml 序列化它:
StringWriter xml = new StringWriter();
Serializer serializer = new Persister();
serializer.write(newhistory, xml);
它仍然在生成的 xml 中读取 0:
<?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>
我猜测其原因是ID 属性不为空,因为整数不能为空。但我确实需要删除这个节点,而且我不想手动删除它。
有人有任何线索吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的“问题”是您使用原始类型(int,char,byte,...)。
在 Java 中,您可以使用原始包装对象(Integer、Chat、Byte)来代替,这样它们就会像任何其他对象一样被处理并且可以为 null。感谢 自动装箱< /a> 您可以将基元分配给它们的对象变体。
所以我建议改变你的模型,如下所示:
还有魔法!节点消失了! ;-)
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:
And magic! The node has disappeared! ;-)