Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding fields in JAXB

I have 2 classes:

@XmlRootElement public class A {      private Long id;     private B b;      // setters and getters } 

and

@XmlRootElement public class B {      private Long id;     private String field1;     private String field2;      // setters and getters } 

By default, if I transform an instance of class A to the XML, I will have all its fields (id) and the referenced B class fields (id, field1, field2) like this:

<a>     <id>2</id>     <b>         <id>5</id>         <field1>test1</field1>         <field2>test3</field2>     </b> </a> 

Is is possible to modify what fields from referenced class B are included in the XML of the A class? E.g. I want to say that when I transform an instance of A class, I just want to get id from the B class (no field1 and field2 fields), so I want to get:

<a>     <id>2</id>     <b>         <id>5</id>     </b> </a> 

I don't want to permanently annotate the B class (using @XMLTransient or @XMLElement) to achieve it, as there are cases in which I want to export whole B class as is (with id, field1 and field2.)
I just don't want to export all these fields when the B class is referenced from A.

Is this even possible with JAX-B?

like image 546
Piotr Nowicki Avatar asked Jun 10 '12 12:06

Piotr Nowicki


People also ask

How do I ignore fields in JAXB?

You can use annotation @XmlTransient to ignore fields. Put this annotation on field itself or its getter.

How do I ignore a field in XML?

Ignore XML Attribute. You can specify ignore="true" or ignore="false". The default value is false. Specifying ignore="false" has no effect on the attribute value assigned when an object of the type specified in the rule is created and no effect on the constraints.

What is @XmlTransient?

The @XmlTransient annotation is useful for resolving name collisions between a JavaBean property name and a field name or preventing the mapping of a field/property. A name collision can occur when the decapitalized JavaBean property name and a field name are the same.


1 Answers

You can use annotation @XmlTransient to ignore fields. Put this annotation on field itself or its getter.

like image 108
AlexR Avatar answered Sep 21 '22 17:09

AlexR