gpt4 book ai didi

java - 以下 xml 的 jaxb 注释

转载 作者:行者123 更新时间:2023-12-01 09:33:13 25 4
gpt4 key购买 nike

我读过有关 JAXB 的内容,但我对此很陌生。我想要从我的类中获取以下 xml

<response>
<command></command>
<message></message>
</response>

这是我的类(class)

抽象父类 - Response

@XmlRootElement
abstract class Response {
String command;

public Response() {
// TODO Auto-generated constructor stub
}

public Response(String command) {
this.command = command;
}

@XmlElement
public String getCommand() {
return command;
}

public void setCommand(String command) {
this.command = command;
}
}

子类:MessageResposne

@XmlRootElement
class MessageResponse extends Response {
String message;

public MessageResponse() {
// TODO Auto-generated constructor stub
}

public MessageResponse(String command, String message) {
super(command);
this.message = message;
}

@XmlElement
public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}

在主类中

try {
objContext = JAXBContext.newInstance(Response.class);
objMarshaller = objContext.createMarshaller();
} catch (JAXBException e) {
e.printStackTrace();
}

但这就是产品

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><response><command>setname</command></response>

我必须进行哪些操作才能获得所需的响应

最佳答案

@XmlSeeAlso 有帮助吗?

@XmlRootElement
@XmlSeeAlso({MessageResponse.class})
abstract class Response {
String command;

public Response() {
// TODO Auto-generated constructor stub
}

public Response(String command) {
this.command = command;
}

@XmlElement
public String getCommand() {
return command;
}

public void setCommand(String command) {
this.command = command;
}
}

它告诉 JAXB 在绑定(bind) Response 时也绑定(bind) MessageReponse

此外,MessageResponse 类必须与 response 元素名称关联,方法是将 MessageResponse.java 的第一行更改为:

@XmlRootElement(name="response")

我可以使用以下主类重现所需的输出:

package test;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main{
public static void main(String[] args)
{
try {
JAXBContext objContext = JAXBContext.newInstance(Response.class);
Marshaller objMarshaller = objContext.createMarshaller();
objMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
MessageResponse mr = new MessageResponse("", "");
objMarshaller.marshal(mr, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}

关于java - 以下 xml 的 jaxb 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39225821/

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