Code Guru
Code Guru

Reputation: 15578

jaxb annotation for following xml

I read about JAXB and I am new to this. I want following xml from my classes

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

Here are my classes

Abstract Parent 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;
}
}

Child class : 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;
}

}

and in main class

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

but this is produces

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

What manipulation I have to do for desired resposne

Upvotes: 0

Views: 48

Answers (1)

Ghislain Fourny
Ghislain Fourny

Reputation: 7279

Would @XmlSeeAlso help?

@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;
  }
}

It tells JAXB to also bind MessageReponse when binding Response.

Also, the MessageResponse class must be associated with the response element name by changing the first line of MessageResponse.java to:

@XmlRootElement(name="response")

I could reproduce the desired output with the following Main class:

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();
    }
  }
}

Upvotes: 1

Related Questions