Java has a transient keyword which is used with default serialization to indicate a value that should not be serialized. However, if I use XML serialization with XMLDecoder the properties associated with that field are still serialized. I tried the same in JSON with the Gson library and transient fields do seem to be properly skipped.
Any ideas why?
XML encoders/decoders favor the @XMLTransient
annotation.
The transient
keyword is for the java object serialization process which ends up in byte sequences. XML "serialization" ends up in a formatted text document. There might be different aspects when you choose a field not to serialize (by marking it transient
) and since the output is quite different, you might wanna choose different fields that you want to exclude and handle them yourself. For example in case of Java serialization you might want to choose to serialize a byte[]
because it is easy and straightforward. In case of XML you might want to serialize the object that was used to create that byte array if it has a nicer/more meaningful text representation.
@XMLTransient
is used by JAXB
. For XMLEncoder
to exclude a field (mark it transient), you have to set a "transient"
property to TRUE
in their PropertyDescriptor
: (source)
BeanInfo info = Introspector.getBeanInfo(JTextField.class);
PropertyDescriptor[] propertyDescriptors =
info.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor pd = propertyDescriptors[i];
if (pd.getName().equals("text")) {
pd.setValue("transient", Boolean.TRUE);
}
}
It's not an elegant solution. An alternative is to use JAXB
instead of XMLEncoder
.