我有一个用Jersey用Java创建的REST API。对于一个请求,我想在JSON中返回一对坐标对的元组列表。为此,我有一个类,它是ArrayList
,Tuple2
类和Coords
类的包装。我使用javax.xml.bind.annotations
自动生成我的类的XML / JSON。
但是由于我不理解我的Coords
类无法将我映射到XML。
我尝试了不同类型的属性(Integers
而不是int
),@XmlAttribute
在不同位置(属性之前和吸气剂之前)和不同的XmlAccessType
(PROPERTY
而不是NONE
]),但结果相同。
这是我的Coords课:
package model;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAttribute;
import static javax.xml.bind.annotation.XmlAccessType.NONE;
@XmlRootElement
@XmlAccessorType(NONE)
public class Coords {
@XmlAttribute private int x;
@XmlAttribute private int y;
public Coords(final int x, final int y) {
this.x = x;
this.y = y;
}
public Coords() {
this.x = 0;
this.y = 0;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
这是它在我的Tuple2中的显示方式
package model;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAttribute;
import static javax.xml.bind.annotation.XmlAccessType.NONE;
@XmlRootElement
@XmlAccessorType(NONE)
public class Tuple2 {
private Coords c1;
private Coords c2;
// ...
@XmlAttribute
public Coords getFirst() {
return this.c1;
}
@XmlAttribute
public Coords getSecond() {
return this.c2;
}
// ...
}
这里是错误消息:
[EL Warning]: moxy: 2019-10-27 15:01:08.586--javax.xml.bind.JAXBException:
Exception Description: The @XmlAttribute property first in type model.Tuple2 must reference a type that maps to text in XML. model.Coords cannot be mapped to a text value.
- with linked exception:
[Exception [EclipseLink-50096] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.JAXBException
Exception Description: The @XmlAttribute property first in type model.Tuple2 must reference a type that maps to text in XML. model.Coords cannot be mapped to a text value.]
oct. 27, 2019 3:01:08 PM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
GRAVE: MessageBodyWriter not found for media type=application/json, type=class model.ActionList, genericType=class model.ActionList.
谢谢您的帮助。
您的问题来自滥用xml注释。通过使用Tuple2
注释将@XmlRootElement
定义为xml根元素,通过使用@XmlAttribute
注释get方法将其字段定义为xml属性。转换为: