Xstream:隐式忽略所有字段
如何告诉 Xstream 仅序列化显式注释的字段并忽略其余字段?
我正在尝试序列化一个 hibernate 持久对象,并且所有与代理相关的字段都被序列化,而我不希望在 xml 中出现这些字段。
eg
<createdBy class="com..domain.Users " reference="../../values/createdBy"/>
不是我想要的 xml 内容。
编辑:我认为我没有说清楚这个问题。一个类可能继承自一个基类,而我无法控制该基类的属性(如在 hibernate 的情况下)。
public class A {
private String ShouldNotBeSerialized;
}
public class B extends A {
@XStreamAlias("1")
private String ThisShouldbeSerialized;
}
在这种情况下,当我序列化类 B 时,基类字段 ShouldNotBeSerialized 也将被序列化。这不是我想要的。在大多数情况下,我无法控制 A 类。
因此,我想默认情况下省略所有字段,并仅序列化我显式指定注释的字段。我想避免 GaryF 正在做的事情,在我需要的地方明确指定我需要省略的字段。
How do I tell Xstream to serialize only fields which are annotated explicitly and ignore the rest?
I am trying to serialize a hibernate persistent object and all proxy related fields get serialized which I don’t want in my xml.
e.g.
<createdBy class="com..domain.Users " reference="../../values/createdBy"/>
is not something I want in my xml.
Edit: I don’t think I made this question clear. A class may inherit from a base class on which I have no control (as in hibernate’s case) on the base class properties.
public class A {
private String ShouldNotBeSerialized;
}
public class B extends A {
@XStreamAlias("1")
private String ThisShouldbeSerialized;
}
In this case when I serialize class B, the base class field ShouldNotBeSerialized will also get serialized. This is not something I want. In most circumstances I will not have control on class A.
Therefore I want to omit all fields by default and serialize only fields for which I explicitly specify the annotation. I want to avoid what GaryF is doing, where I need to explicitly specify the fields I need to omit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 @XstreamOmitField 注释省略字段。直接来自手册:
You can omit fields with the @XstreamOmitField annotation. Straight from the manual:
我不能相信这个答案,只是分享我所发现的。您可以重写XStream类的wrapMapper方法来实现您所需要的。
此链接详细说明: http://pvoss.wordpress.com/2009/01/ 08/xstream/
如果您不需要解释,这里是您需要的代码:
您可能希望在实现此代码之前完成所有测试,因为默认 XStream 对象抛出的异常对于查找拼写很有用错误。
I can take no credit for this answer, just sharing what I have found. You can override the wrapMapper method of the XStream class to achieve what you need.
This link explains in detail: http://pvoss.wordpress.com/2009/01/08/xstream/
Here is the code you need if you don't want the explanation:
You might want to do all your testing before you implement this code because the exceptions thrown by the default XStream object are useful for finding spelling mistakes.
已经有一张给 XStream 人员的票了:
http://jira.codehaus.org/browse/XSTR-569
There was already a ticket for the XStream people:
http://jira.codehaus.org/browse/XSTR-569
我想唯一直接的方法是深入编写 MapperWrapper 并排除所有未注释的字段。听起来像是对 XStream 的功能请求。
I guess the only direct way is to dive into writing a MapperWrapper and exclude all fields you have not annotated. Sounds like a feature request for XStream.