Skip to content
Advertisement

How to use setters in JAXB collections unmarshalling

I wan’t to deserialize XML to my POJO but something doing wrong…

My POJO class:

JavaScript

Marshalling example:

JavaScript

XML output:

JavaScript

Unmarshalling example:

JavaScript

Console output:

JavaScript

As you can see, citiesId is empty. It happens because JAXB unmarshalling calling the getter (copy of field in my case) and trying to set values into a copy of collection. How to make it create a collection and set it via setter?

P.S. In my real bussiness object, i have collect IDs in getter from DB entities, and cannot return collection in getter.

Thanks!

Advertisement

Answer

—- Edited last time —–

JavaScript

Printout:

JavaScript

During unmarshalling JAXB checks if your collection is null, if it is (It will call the setter for the first time to initialize it to empty), and you can see that in the log.

However, afterwards, it will use its internal logic to populate the collection (SET), initialize its type (New Set)*by using the Setter you have, and use the Set.add(xyz); to add (1), then (5).

The JAXB Logic invoked is found in class:

JavaScript

//startPacking is calling to initialize the collection Set so it is empty

JavaScript

//Right way, this gets called afterwards (Before any of your TaxiEntity logic), to do addToPack(1), addToPack(5), <— Now your Set has [1,5]

JavaScript

Then, you see in the log, it calls getCitiesIds(), and you will see magically it has [1,5]

Its the way JAXB works with Collections. All other elements, their proper Setters are called.

See, JAXB does not call Setter method

You need to think of a different way of doing it, rather than dependending on the getter/setter. It did its job of unmarshalling the object from the XML file, the rest of the logic could be written in an external method.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement