Use annotation other than XstreamAlias to serialize an object with XStream

3.7k views Asked by At

I have a java class in which members are annotated with the XstreamAlias annotation. Under some conditions I would like to output the same class (and its members recursively) with different annotations. How can I ask Xstream to use method/class annotations that are not the @XstreamAlias annotation?

1

There are 1 answers

3
Dalija Prasnikar On

You cannot make XStream to use different annotations, but you can define different aliases in code.

@XStreamAlias("abc")
public class Abc
{
    @XStreamAlias("bb")
    public String a;
}

When you serialize above class with annotations you will get following xml

<abc>
  <bb>something</bb>
</abc>

When you disable annotations and define new aliases

XStream xstream = new XStream();
xstream.autodetectAnnotations(false);
xstream.alias("xxx", Abc.class);
xstream.aliasField("ccc", Abc.class, "a");

you will get different xml output

<xxx>
  <ccc>something</ccc>
</xxx>

List of available alias methods:

Alias a Class to a shorter name to be used in XML elements.

public void alias(String name, Class type)

Alias a type to a shorter name to be used in XML elements. Any class that is assignable to this type will be aliased to the same name.

public void aliasType(String name, Class type)

Alias a Class to a shorter name to be used in XML elements. defaultImplementation represents default implementation of type to use if no other specified.

public void alias(String name, Class type, Class defaultImplementation)

Alias a package to a shorter name to be used in XML elements.

public void aliasPackage(String name, String pkgName)

Create an alias for a field name.

public void aliasField(String alias, Class definedIn, String fieldName)

Create an alias for an attribute

public void aliasAttribute(String alias, String attributeName)

Create an alias for a system attribute. XStream will not write a system attribute if its alias is set to <code>null</code>. However, this is not reversible, i.e. deserialization of the result is likely to fail afterwards and will not produce an object equal to the originally written one.

public void aliasSystemAttribute(String alias, String systemAttributeName)

Create an alias for an attribute.

public void aliasAttribute(Class definedIn, String attributeName, String alias)