2

如何告诉 Xstream 仅序列化显式注释的字段并忽略其余字段?

我正在尝试序列化一个休眠持久对象,并且所有与代理相关的字段都被序列化,这在我的 xml 中是我不想要的。
例如

<createdBy class="com..domain.Users " reference="../../values/createdBy"/>

不是我想要在我的 xml 中的东西。

编辑:我不认为我把这个问题说清楚了。一个类可以从一个基类继承,而我对基类属性没有控制(如在休眠的情况下)。

public class A {
    private String ShouldNotBeSerialized;
}

public class B extends A {
    @XStreamAlias("1")
    private String ThisShouldbeSerialized;
}

在这种情况下,当我序列化 B 类时,基类字段ShouldNotBeSerialized也会被序列化。这不是我想要的。在大多数情况下,我无法控制 A 类。

因此,我想默认省略所有字段并仅序列化我明确指定注释的字段。我想避免GaryF正在做的事情,我需要明确指定我需要省略的字段。

4

4 回答 4

3

您可以使用 @XstreamOmitField 注释省略字段。直接从手册:

@XStreamAlias("message")
class RendezvousMessage {

    @XStreamOmitField
    private int messageType;

    @XStreamImplicit(itemFieldName="part")
    private List<String> content;

    @XStreamConverter(SingleValueCalendarConverter.class)
    private Calendar created = new GregorianCalendar();

    public RendezvousMessage(int messageType, String... content) {
        this.messageType = messageType;
        this.content = Arrays.asList(content);
    }
}
于 2010-01-04T09:17:07.487 回答
3

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:

    // Setup XStream object so that it ignores any undefined tags
    XStream xstream = new XStream() {
            @Override
            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {
                    @Override
                    public boolean shouldSerializeMember(Class definedIn,
                            String fieldName) {
                        if (definedIn == Object.class) {
                            return false;
                        }
                        return super
                                .shouldSerializeMember(definedIn, fieldName);
                    }
                };
            }
        };

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.

于 2013-08-03T20:13:13.537 回答
2

XStream 的人已经有一张票了:

Again, this is by design. XStream is a serialization tool, not a data binding tool. It is made to serialize Java objects to XML and back. It will write anything into XML that is necessary to recreate an equal object graph. The generated XML can be tweaked to some extend by configuration for convenience, but this is already an add-on. What you like to do can be done by implementing a custom mapper, but that's a question for the user's list and cannot be handled here.

http://jira.codehaus.org/browse/XSTR-569

于 2012-05-27T16:53:24.503 回答
1

我想唯一直接的方法是深入编写 MapperWrapper 并排除所有未注释的字段。听起来像是对 XStream 的功能请求。

于 2010-02-23T23:36:37.457 回答