为什么不能将这个简单的对象映射到Java / Jersey中XML的文本中?

问题描述 投票:2回答:1

我有一个用Jersey用Java创建的REST API。对于一个请求,我想在JSON中返回一对坐标对的元组列表。为此,我有一个类,它是ArrayListTuple2类和Coords类的包装。我使用javax.xml.bind.annotations自动生成我的类的XML / JSON。

但是由于我不理解我的Coords类无法将我映射到XML。

我尝试了不同类型的属性(Integers而不是int),@XmlAttribute在不同位置(属性之前和吸气剂之前)和不同的XmlAccessTypePROPERTY而不是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.

谢谢您的帮助。

java jaxb jersey moxy
1个回答
0
投票

您的问题来自滥用xml注释。通过使用Tuple2注释将@XmlRootElement定义为xml根元素,通过使用@XmlAttribute注释get方法将其字段定义为xml属性。转换为:

© www.soinside.com 2019 - 2024. All rights reserved.