CodeGym /Java Course /Java Collections /Complex serialization to XML, JAXB (nested classes, etc.)...

Complex serialization to XML, JAXB (nested classes, etc.)

Java Collections
Level 3 , Lesson 9
Available

"Okay, then. As you've probably already guessed, that wasn't everything."

"Now I'll tell you about several other aspects of JAXB. But as we did with JSON, we will begin with collections."

"When deserializing collections using JAXB, there is also uncertainty about which particular collection (ArrayList, LinkedList, Vector, etc.) to use for the List variable. And again the answer to this question is provided by annotations."

"It's all pretty simple. If the collection type is not specified in its annotation, then JAXB will try to select the most appropriate collection using its type. For a List, this will be ArrayList; for a Map, it will be HashMap, etc."

"In reality, there are far fewer problems here than with JSON, because each class has a unique tag, and you can use the tag to specify the exact class."

"For example, if you need to deserialize a group of elements that inherit a common ancestor, you use the @XmlAny: annotation"

Convert an object from XML
public static void main(String[] args) throws JAXBException
{
 String xmldata = "<zoo><cat/><cat/><dog/><cat/></zoo>";
 StringReader reader = new StringReader(xmldata);

 JAXBContext context = JAXBContext.newInstance(Cat.class, Zoo.class, Dog.class);
 Unmarshaller unmarshaller = context.createUnmarshaller();

 Cat cat = (Cat) unmarshaller.unmarshal(reader);
}
A class whose objects are deserialized from XML
@XmlType(name = "zoo")
@XmlRootElement
class Zoo
{
 @XmlAny
 public List<Object> animals;
}

@XmlType(name = "cat")
@XmlRootElement
class Cat
{
 public String name;
 public int age;
 public int weight;

 Cat()
 {
 }
}

@XmlType(name = "dog")
@XmlRootElement
class Dog
{
 public String name;
 public int age;
 public int weight;

 Cat()
 {
 }

"If a collection is marked with the @XmlAny annotation, then any suitable objects can be put in it. And the JAXB Unmarshaller pays attention to the tags when populating the collection."

"In this case, the sequence of tags "<zoo><cat/><cat/><dog/><cat/></zoo>" will be converted into a collection with Cat, Cat, Dog, and Cat objects."

"That's about what I expected."

"Uh-huh. Oh, by the way, one more thing. If you deserialize a mixture of text and tags, you need to use the @XmlMixed annotation."

"Here's an example of this type of XML:"

Sample XML that requires the @XmlMixed annotation
<data>
<items>
 test 1
<item/>
 text 2
<item>
 name
</item>
 text 3
</items>
</data>

"Wow. I had forgotten that such XML exists. I got used to everything being pretty, with embedded tags, and everything else."

"It does exist. And JAXB has an annotation even for this case!"

"Great. By the way, I wanted to ask: how are enums serialized?"

"Good question! Nice catch! I somehow skipped that topic."

"There is a special @XmlEnum annotation that must be used to mark enums. You can use it to specify whether the values will be stored as numbers or strings."

"There is also a @XmlEnumValue annotation that lets you specify the value that will correspond to a particular enum field."

"Here are some examples:"

Numbers Strings
@XmlType
@XmlEnum(Integer.class)
public enum Code
{
 @XmlEnumValue("1")
  START,

 @XmlEnumValue("2")
  INPROGRESS,

 @XmlEnumValue("3")
  FINISH

 @XmlEnumValue("-1")
  ERROR
}
@XmlType
@XmlEnum(String.class)
public enum Card
{
 @XmlEnumValue("Spade")
  CLUBS,

 @XmlEnumValue("Diamond")
  DIAMONDS,

 @XmlEnumValue("Heart")
  HEARTS,

 @XmlEnumValue("Club")
  SPADES
}

"Holy moly. I can't imagine where I would need this, but I think it's very useful. And most importantly, I don't have to stick to standard string or numeric values."

"Yep. This is handy, for example, when you write a program that exchanges messages with, say, a Facebook server, and they have an assigned set of values. You just need to assign them to their own enum and everything will work."

"That's wonderful. I definitely like JAXB."

"Great. Then that's it for today. Go and take a break."

Comments (6)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Lisa Level 41
2 January 2022
I can not find a XmlAny annotation. I even looked that up in the JavaEE7 documentation and you guys probably meant XmlAnyElement In the first example (Convert an object from XML) a Cat object gets created (or not, cause that fails) but the input is a XML that represents a Zoo object. So probably a Zoo object should be created (that works if the Dog constructor gets fixed and @XmlAnyElement used).

((Zoo) unmarshaller.unmarshal(reader)).animals.forEach(System.out::println);
matemate123 Level 50, Kraków, Poland
15 September 2023
Thank you, I thought that I don't have some annotation library still
Andrei Level 41
28 June 2021
What the hell am I reading? 😂
MaGaby2280 Level 41, Guatemala City, Guatemala
9 June 2021
Just remember JAXB has been deprecated since Java 11
Andrei Level 41
28 June 2021
I wonder since it has been deprecated, is it still in use somewhere? Should we bother trying to understand JAXB ?
MaGaby2280 Level 41, Guatemala City, Guatemala
30 June 2021
Yes, there are still many programs that use it