A Technology Blog About Code Development, Architecture, Operating System, Hardware, Tips and Tutorials for Developers.

Showing posts with label JAXB. Show all posts
Showing posts with label JAXB. Show all posts

Thursday, December 20, 2012

List and Set implementations are not marshalled with JAXB?

7:09:00 PM Posted by Satish , , , No comments
Snap of code what I was doing:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@XmlRootElement
public class FooBar {
  public String title;
  public FooBar(String t) {
    this.title = t;
  }
}
@XmlRootElement
@XmlSeeAlso({FooBar.class})
public class FooBarSet extends ArrayList<FooBar> {
  public FooBarSet() {
    this.add(new FooBar("FooBar"));
  }
}

Then, while marshaling:

1
2
3
JAXBContext ctx = JAXBContext.newInstance(FooBar.class);
Marshaller msh = ctx.createMarshaller();
msh.marshal(new FooBar(), System.out);

This is what I saw:

1
2
<?xml version="1.0"?>
<FooBarSet/>

Why I am not getting the list of FooBar ??????

The Answer is the elements to be marshalled must be public, or have the @XMLElement anotation. The ArrayList class and my class FooBarSet do not match any of these rules. I have to define a method to offer the FooBar values, and anotate it.


So the modified class is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@XmlRootElement
@XmlSeeAlso({FooBar.class})
public class FooBarSet extends ArrayList<FooBar> {
  public FooBarSet() {
    this.add(new FooBar("FooBar"));
  }

  @XmlElement(name = "FooBar")
 public List<FooBar> getFooBarSet() {
     return this;
 }
}

Now the output:

1
2
3
4
5
<fooBarSet>
 <FooBar>
  <title>FooBar</title>
 </FooBar>
</fooBarSet>