2

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?

icza
  • 389,944
  • 63
  • 907
  • 827
sproketboy
  • 8,967
  • 18
  • 65
  • 95

1 Answers1

3

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.

icza
  • 389,944
  • 63
  • 907
  • 827
  • You might wanna use the same class for Java serialization and XML encoding. If you only have 1 keyword or way to mark excluded fields, you could not make a difference for the 2 purpose. – icza Sep 17 '14 at 12:27
  • Yeah, for `XMLEncoder` it doesn't. `@XMLTransient` is for `JAXB`. Edited to clarify this and added an exmaple howto do it with `XMLEncoder`. – icza Sep 17 '14 at 12:33
  • Right. I know about that. I need to iterate across properties at runtime to indicate it. That's just retarded since Java has a transient keyword. – sproketboy Sep 17 '14 at 13:01