我有不同的Response
类用于不同的Rest调用。但他们都处理相同的Entity
。
最初我是因为没有告诉JaxB来自Response类的实体类。它是使用@XmlSeeAlso({Entity.class})
解决的。现在我正在尝试修复Response
中的根元素名称
。类
的 Issue1:
@XmlRootElement(name="?")
@XmlSeeAlso({Entity.class})
public class FindAllResponse
extends ListResponse<Entity>
{
/**
* serial version uid
*/
private static final long serialVersionUID = xxx;
}
预期回应是
<Response>
<Entities>
<Entity></Entity>
</Entities>
<Response>
如何将<Response><Entities>
root添加到上面的响应类中。
的 Issue2:
@XmlRootElement(name="?")
@XmlSeeAlso({Entity.class})
public class FindEntityResponse
extends Response<JobType>
{
@JsonUnwrapped
public Entity getValue() {
return super.getValue();
}
}
在这种情况下,预期的响应没有任何根元素。预期响应xml只是从<Entity></Entity>
开始
使用@XmlTransient
和问题1的@XmlRootElement
尝试但没有运气。
答案 0 :(得分:0)
您需要将Entity
类包装在分别定义Response
和Entities
的根元素的类中。
像基本的东西:
// this class will represent your Response element and all attributes
@XmlRootElement(name="Response")
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {
@XmlElement(name="Entities")
private Entities myEntities;
public Response() {
myEntities = new Entities();
}
public Entities getMyEntities() { return myEntities; }
public void setMyEntities(Entities entities) { this.myEntities = entities; }
}
// this class will represent the collection of Entities
@XmlRootElement(name="Entities")
@XmlAccessorType(XmlAccessType.FIELD)
public class Entities {
@XmlElement(name="Entity")
private List<Entity> entities;
public Entities() {
entities = new ArrayList<Entity>();
}
public List<Entity> getEntities() { return this.entities; }
public void setEntities(List<Entity> entities) { this.entities = entities; }
}
// a simple Entity class (I don't know what yours is)
@XmlRootElement(name="Entity")
@XmlAccessorType(XmlAccessType.FIELD)
public class Entity {
@XmlAttribute(name="id")
private String id;
public Entity() {}
public Entity(String id) { setId(id); }
public String getId() { return id; }
public void setId(String id) { this.id = id; }
}
最后,一个简单的测试:
public class Test {
public static void main(String[] args) throws Exception {
Response r = new Response();
Entities e = new Entities();
e.getEntities().add(new Entity("1"));
e.getEntities().add(new Entity("2"));
e.getEntities().add(new Entity("3"));
r.setMyEntities(e);
JAXBContext context = JAXBContext.newInstance(Response.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(r, System.out);
}
}
产生以下输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Response>
<Entities>
<Entity id="1"/>
<Entity id="2"/>
<Entity id="3"/>
</Entities>
</Response>
我认为这可以让你更接近你所追求的目标。