2016-08-30 3 views
0

JAXBについて読んだことがあります。 MessageResposne次のXMLのためのjaxb注釈

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

} 

とメインクラスで

:レスポンス

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

子クラス - 私はここで

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

は、私のクラスは

抽象親クラスで私のクラスから次のXMLをしたいです

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

が、これは、私が希望resposne

答えて

1

@XmlSeeAlso助けのために何をすべきかの操作

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

を生成しますか?

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

それはResponseをバインドするときにもMessageReponseをバインドするためにJAXBに指示します。

また、MessageResponseクラスはへMessageResponse.javaの最初の行を変更することにより、response要素名に関連付けられている必要があります。私は、次のメインクラスで所望の出力を再現することができ

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

エラーを表示しています:[致命的なエラー]:1:56:ファイルの早すぎる終了。 のjava.lang.NullPointerException –

+0

私はクラスをMessageResponseする@​​XmlRootElementを追加し、

+0

この生成され SETNAME私のメッセージは、これはよさそうです。最後に欠けているのは、XmlRootElementの 'name'属性です。私は答えを編集しました。 –

関連する問題