[英]How to use the @Transient annotation when using JavaBeanConverter in XStream?
I am trying to serialise some POJOs to XML. 我正在尝试将一些POJO序列化为XML。 Some of them use
@Transient
annotations to indicate that some properties should not be serialised. 其中一些使用
@Transient
批注指示某些属性不应序列化。
I have made a small test case to demonstrate the problem. 我做了一个小测试用例来演示该问题。 I have also tried using
@XStreamOmit
but the result is the same. 我也尝试过使用
@XStreamOmit
但结果是相同的。 I do NOT expect to see the HiddenTop
property in the output. 我不希望在输出中看到
HiddenTop
属性。
The POJO: 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;
}
}
The Main: 主要的:
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();
}
}
}
The output 输出
<test.DerivedObject>
<hiddenTop>:-(</hiddenTop>
<visibleTop>:-)</visibleTop>
</test.DerivedObject>
Becouse JavaBeanProvider
doesn't respect the @Transient
annotation a solution is to implement you own JavaBeanProvider
that respect this annotation: 因为
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;
}
}
You can use it as follows: 您可以按以下方式使用它:
final JavaBeanProvider beanProvider = new TransientRespectingBeanProvider();
final Converter converter = new JavaBeanConverter(xstream.getMapper(), beanProvider);
xstream.registerConverter(converter);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.