Jersey, JAXB and getting an object extending an abstract class as a parameter

I want to get an object as a POST request parameter. I got an abstract superclass called Promotion and subclasses of Product and Percent . This is how I try to get the request:

 @POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) @Path("promotion/") public Promotion createPromotion(Promotion promotion) { Product p = (Product) promotion; System.out.println(p.getPriceAfter()); return promotion; } 

and here, as I use JAXB in class definitions:

 @XmlRootElement(name="promotion") @XmlSeeAlso({Product.class,Percent.class}) public abstract class Promotion { //body } @XmlRootElement(name="promotion") public class Product extends Promotion { //body } @XmlRootElement(name="promotion") public class Percent extends Promotion { //body } 

So now the problem is sending a POST request with a body like this:

 <promotion> <priceBefore>34.5</priceBefore> <marked>false</marked> <distance>44</distance> </promotion> 

and I'm trying to pass it to Product (since in this case the fields "marked" and "distance" belong to the Promotion class, and "priceBefore" refers to the Product class). I get an exception:

 java.lang.ClassCastException: Percent cannot be cast to Product. 

Percent seems to be selected as a subclass of "default". Why is this and how can I get an object that is Product ?

+4
source share
1 answer

Since you have an entire inheritance hierarchy with the same root element, you need to use the xsi:type attribute to indicate the appropriate subtype.

 <promotion xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="product"> <priceBefore>34.5</priceBefore> <marked>false</marked> <distance>44</distance> </promotion> 

Additional Information


UPDATE

Another thing to try is to give each subtype a different @XmlRootElement

 @XmlRootElement // defaults to "product" public class Product extends Promotion { //body } 

Then send the following XML:

 <product> <priceBefore>34.5</priceBefore> <marked>false</marked> <distance>44</distance> </product> 
0
source

Source: https://habr.com/ru/post/1443684/


All Articles