gpt4 book ai didi

java - 在XStream中使用JavaBeanConverter时如何使用@Transient注解?

转载 作者:行者123 更新时间:2023-11-30 03:52:59 25 4
gpt4 key购买 nike

我正在尝试将一些 POJO 序列化为 XML。其中一些使用 @Transient 注释来指示某些属性不应被序列化。

我做了一个小测试用例来演示这个问题。我也尝试过使用@XStreamOmit,但结果是相同的。我不希望在输出中看到 HiddenTop 属性。

POJO:

package test;

import java.beans.Transient;
import com.thoughtworks.xstream.annotations.XStreamOmitField;

public class DerivedObject
{
private String xVisible = "GOODTOP";
private String xHidden = "BADTOP";

public DerivedObject() {
}

public String getVisibleTop() {
return xVisible;
}

public void setVisibleTop(String xVisible) {
this.xVisible = xVisible;
}

@Transient
public String getHiddenTop() {
return xHidden;
}

@Transient
public void setHiddenTop(String xHidden) {
this.xHidden = xHidden;
}
}

主要:

package test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.javabean.JavaBeanConverter;

public class TestAnnotation
{
public static void main(String[] args) {
DerivedObject o = new DerivedObject();
o.setVisibleTop(":-)");
o.setHiddenTop(":-(");
try {
XStream xs = new XStream();
xs.autodetectAnnotations(true);
xs.registerConverter(new JavaBeanConverter(xs.getMapper()),
XStream.PRIORITY_LOW);
System.out.println(xs.toXML(o));
}
catch (Exception e) {
e.printStackTrace();
}
}
}

输出

<test.DerivedObject>
<hiddenTop>:-(</hiddenTop>
<visibleTop>:-)</visibleTop>
</test.DerivedObject>

最佳答案

因为 JavaBeanProvider 不遵守 @Transient 注释,解决方案是实现您自己的遵守此注释的 JavaBeanProvider:

    public class TransientRespectingBeanProvider extends BeanProvider {
@Override
protected boolean canStreamProperty(PropertyDescriptor descriptor) {
final boolean canStream = super.canStreamProperty(descriptor);
if (!canStream) {
return false;
}

final boolean readMethodIsTransient = descriptor.getReadMethod() == null
|| descriptor.getReadMethod().getAnnotation(Transient.class) != null;
final boolean writeMethodIsTransient = descriptor.getWriteMethod() == null
|| descriptor.getWriteMethod().getAnnotation(Transient.class) != null;
final boolean isTransient = readMethodIsTransient
|| writeMethodIsTransient;

return !isTransient;
}
}

您可以按如下方式使用它:

    final JavaBeanProvider beanProvider = new TransientRespectingBeanProvider();
final Converter converter = new JavaBeanConverter(xstream.getMapper(), beanProvider);
xstream.registerConverter(converter);

关于java - 在XStream中使用JavaBeanConverter时如何使用@Transient注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23913606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com