带接口的REST API - JAXB

时间:2014-03-04 19:46:24

标签: java rest jaxb

我在Java中使用接口的实现。 例如:可以有许多PaymentTypes,如信用卡,手机等。 我正在制作一个包含接口的REST API - 如何在JAXB中映射它,目前它给我发生了JAXBException:2个IllegalAnnotationExceptions计数。

目前我正在使用Apache-CXF和JAXb

@XmlRootElement
public class Payment {
    @XmlElement
    private PaymentType paymentType;
    @XmlElement
    private long price;

    public Payment() {
    }

    public Payment(final PaymentType paymentType, final long price) {
        super();
        this.paymentType = paymentType;
        this.price = price;
    }
}

@Path("/trial")
public class TrialService {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Payment> getPayments() {
        final List<Payment> payments = new LinkedList<Payment>();
        final CreditCardDetails creditCard = new CreditCardDetails(
                "8767798778", "123", 12, 2016);
        final Payment payment = new Payment(creditCard, 10);
        payments.add(payment);
        return payments;
    }
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public PaymentDetails startPayment(final PaymentDetails paymentDetails) {
    return paymentDetails;
}
}

public class CreditCardDetails implements PaymentType {

    @XmlElement
    private String creditCardNumber;
    @XmlElement
    private String cvv;
    @XmlElement
    private int expirationMonth;
    @XmlElement
    private int expirationYear;

    public CreditCardDetails() {
    }

    @SuppressWarnings("javadoc")
    public CreditCardDetails(
            // final BillingAddress billingAddress,
            final String creditCardNumber, final String cvv,
            final int expirationMonth, final int expirationYear) {
        super();
        this.creditCardNumber = creditCardNumber;
        this.cvv = cvv;
        setExpirationMonth(expirationMonth);
        setExpirationYear(expirationYear);
    }
}

我应该如何映射这个或者我应该使用完全不同的方法?

编辑: 对于POST方法,我收到付款。付款可以包含任何对象CreditCard,Wallet等。我应该提供什么注释,以便正确地进行预期。 目前它抛出了一个JAXB异常。

1 个答案:

答案 0 :(得分:2)

您收到的完整错误消息是:

Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions PaymentType is an interface, and JAXB can't handle interfaces.

您需要为元素使用concreate类,或将其指向type注释的@XmlElement属性:

@XmlElement(type = CreditCardDetails.class)
private PaymentType paymentType;

如果您有更多使用PaymentType接口的类,那么您可以使用以下解决方案:

 @XmlAnyElement
 @XmlElementRefs({
    @XmlElementRef(type=CreditCardDetails.class),
    @XmlElementRef(type=Wallet.class)   
 })
 PaymentType paymentType;

@XmlElementRefs列表可以包含任意数量的元素,但必须列出所有可能性。 CreditCardDetailsWallet必须使用@XmlRootElement进行注释。

您可以跳过@XmlElementRefs注释:

@XmlAnyElement(lax=true)
PaymentType paymentType;

但在这种情况下,请确保您在JAXB上下文中有任何必需的类,如果您不使用注册表使用@ PaymentType字段和@XmlSeeAlso({CreditCardDetails.class,Wallet.class})注释您的类。