gpt4 book ai didi

java - JAXB : 2 counts of IllegalAnnotationExceptions

转载 作者:数据小太阳 更新时间:2023-10-29 01:44:15 27 4
gpt4 key购买 nike

这是我的解析器类

public class Test {
public static void main(String args[]) throws Exception {

File file = new File("D:\\Test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(MyOrder.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
MyOrder customer = (MyOrder) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer.getOrder().getSide());
}
}

这是 MyOrder.java 文件

@XmlRootElement(name = "BXML")
public class MyOrder {
@XmlElement(name = "Bag")
protected Order order;

public MyOrder() {

}
@XmlAttribute
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
}

这是我的域对象 (Order.java)

@XmlRootElement(name = "BXML")
public class Order {

public Order() {

}

@XmlAttribute(name = "Side")
protected BigInteger Side;

@XmlValue
public BigInteger getSide() {
return Side;
}

public void setSide(BigInteger side) {
Side = side;
}
}

这是我尝试运行程序时遇到的异常

Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
@XmlAttribute/@XmlValue need to reference a Java type that maps to text in XML.
this problem is related to the following location:
at public com.Order com.MyOrder.getOrder()
at com.MyOrder
Class has two properties of the same name "order"
this problem is related to the following location:
at public com.Order com.MyOrder.getOrder()
at com.MyOrder
this problem is related to the following location:
at protected com.Order com.MyOrder.order
at com.MyOrder

最佳答案

对于 @XmlAttribute/@XmlValue 需要引用映射到 XML 文本的 Java 类型。 问题,您需要将 JAXBContext 的初始化更改为以下内容:

JAXBContext jaxbContext = JAXBContext.newInstance(MyOrder.class, Order.class);

对于类有两个同名属性“order”的问题,需要将定义的protected Order order;修改为private Order order ;

此外,您想将 Order 类的 @XmlRootElement(name = "BXML") 更改为 @XmlRootElement(name = "Order")

关于java - JAXB : 2 counts of IllegalAnnotationExceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9991506/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com