5

JAX-RS ベースの RESTful Web サービスを開発しようとしており、Web サービスの JSON 応答を自動的に生成するために MOXy (JAXB) を使用しています。

すべてがクールですが、Web サービスは JavaScript ベースの Web アプリケーションのバックエンドになるため、一般にアクセス可能になるため、クラス名などの特定の詳細を公開したくありません。

しかし、特定の条件下では、MOXy が "@type" エントリをマーシャリングされた文字列に埋め込み、このエントリの後にマーシャリングされたばかりのオブジェクトのクラス名が続くことに気付きました。

特に、拡張クラスのインスタンスをマーシャリングするときに、MOXy がこのように動作することに気付きました。

次のスーパークラス「MyBasicResponse」を仮定します

@XmlRootElement(name="res")

public class MyBasicResponse {

@XmlElement
private String msg;

public MyBasicResponse() {
    // Just for conformity
}

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}
}

そして、この特化(拡張)クラス「MySpecialResponse」

@XmlRootElement(name="res")

public class MySpecialResponse extends MyBasicResponse {

@XmlElement
private String moreInfo;

public MySpecialResponse() {
    // Just for conformity
}

public String getMoreInfo() {
    return moreInfo;
}

public void setMoreInfo(String moreInfo) {
    this.moreInfo = moreInfo;
}
}

したがって、MyBasicResponse オブジェクトのマーシャリングされた文字列は次のとおりです。

{"msg":"A Message."}

(大丈夫!)

しかし、MySpecialResponse オブジェクトのマーシャリングされた文字列は次のようになります。

{"@type":"MySpecialResponse","msg":"A Message.","moreInfo":"More Information."}

剥がす方法はありますか

"@type":"MySpecialResponse"

私の応答のうち?

4

1 に答える 1

2

JAXBElement型キーを取り除くために、マーシャリングされるサブクラスを指定するインスタンスでオブジェクトをラップできます。以下は完全な例です。

Java モデル

質問と同じですが、package-infoこれらのクラスに一致するようにフィールドアクセスを指定するために次のクラスが追加されています

@XmlAccessorType(XmlAccessType.FIELD)
package com.example.foo;

import javax.xml.bind.annotation.*;

デモコード

デモ

import java.util.*;
import javax.xml.bind.*;
import javax.xml.namespace.QName;

import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {MySpecialResponse.class}, properties);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        MySpecialResponse msr = new MySpecialResponse();
        marshaller.marshal(msr, System.out);

        JAXBElement<MySpecialResponse> jaxbElement = new JAXBElement(new QName(""), MySpecialResponse.class, msr);
        marshaller.marshal(jaxbElement, System.out);
    }

}

出力

MOXy に関してはとを区別する必要があったため、オブジェクトがマーシャリングされたときにtype(XML 表現の属性に対応する) キーがマーシャリングされたことがわかります。オブジェクトを のインスタンスにラップして修飾したとき、MOXy 型にキーを追加する必要はありませんでした。xsi:typeMyBasicResponseMySpecialResponseJAXBElementtype

{
   "type" : "mySpecialResponse"
}
{
}

詳細については

于 2011-06-21T14:15:02.253 に答える