gpt4 book ai didi

java - JAXB:处理根元素

转载 作者:太空宇宙 更新时间:2023-11-04 14:43:53 26 4
gpt4 key购买 nike

我有不同的Response不同 Rest 调用的类。但他们都处理相同的Entity 。最初,我因为没有告诉 JaxB 有关 Response 类中的 Entity 类而感到不舒服。通过使用 @XmlSeeAlso({Entity.class}) 解决了这个问题。现在我正在尝试修复 Response 中的根元素名称类。
问题1:

@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>根到上面的响应类。
问题2:

@XmlRootElement(name="?")
@XmlSeeAlso({Entity.class})
public class FindEntityResponse
extends Response<JobType>
{


@JsonUnwrapped
public Entity getValue() {
return super.getValue();
}

}

在这种情况下,预期响应没有任何根元素。预期响应 xml 以 <Entity></Entity> 开头.
尝试使用@XmlTransient@XmlRootElement对于第 1 期,但运气不佳。

最佳答案

您需要将 Entity 类包装在分别定义 ResponseEntities 根元素的类中。

一些基本的东西,比如:

// 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>

我认为这应该会让你更接近你所追求的目标。

关于java - JAXB:处理根元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24664159/

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