users@jaxb.java.net

Re: Serializing an additional enum field, ignoring it on deserialize

From: Wolfgang Laun <wolfgang.laun_at_gmail.com>
Date: Tue, 14 Jul 2009 08:05:23 +0200

Since you write JAXB-annotated Java, the solution is simple:

add another field as an attribute to your class MyClass. Code the
setter setId for the attribute you want to use in your application
(id, the enum) so that it also sets the other attribute (name, a
String, presumably). Marshalling will give you both values.
Unmarshalling will call both setters (if name="..." is present in the
XML), but the setName() call won't change anything.

-W

On 7/13/09, Pinch, Marnee <Marnee.Pinch_at_pearson.com> wrote:
>
>
>
> Is there a way to serialize an additional enum field as an attribute and
> have it be ignored upon deserialization?
>
>
>
> This is a field that is in addition to the enum value. (We want this for
> readability when looking at the document and possibly for an identifier for
> a user other than the application which is producing the document.)
>
>
>
> For us, we need to ignore the additional attribute upon deserialization.
>
>
>
> A simple example of what I want to do is below.
>
>
>
> I have a class that has a field of type MyEnum. MyEnum has an ‘id’ field
> and a ‘name’ field. I am serializing the enum constants via the id:
>
>
>
> public class MyClass {
>
>
>
> @XmlAttribute(name="id")
>
> MyEnum someEnum;
>
> }
>
>
>
>
>
> @XmlEnum
>
> public enum MyEnum {
>
>
>
> @XmlEnumValue("1")
>
> CONSTANT1(1, "constant1"),
>
>
>
> @XmlEnumValue("2")
>
> CONSTANT2(2, "constant2"),
>
>
>
> @XmlEnumValue("3")
>
> CONSTANT3(3, "constant3"),
>
>
>
> @XmlEnumValue("4")
>
> CONSTANT4(4, "constant4"),
>
>
>
> private final int id;
>
> private final String name;
>
>
>
> MyEnum(int id, String name) {
>
> // snip
>
> }
>
> }
>
>
>
> So, the output for the above is, for example:
>
>
>
> <MyClass id=”1” name=”constant1”/>
>
>
>
> The desired output is:
>
>
>
> <MyClass id=”1” name=”constant1”/>
>
>
>
> Is there any possible way to do this? Note that we are not using a schema.
> We are only using annotations on existing code, although we can make some
> coding changes to accommidate this.
>
>
>
> Thanks for any suggestions.