2

Jettison を使用して、JAXB オブジェクト (@XmlRootElement を含む) を JSON にマーシャリングしました。しかし、@XmlRootElement のようなアノテーションを持たない単純な Java オブジェクトを JSON に変換することはできません。「オブジェクトをJSONにマーシャリングするには、その@XmlRootElementが必須ですか?」と知りたいです。

Java オブジェクトを Json にマーシャリングしようとすると、次の例外が発生します。

com.sun.istack.SAXException2: unable to marshal type "simpleDetail" as an element because it is missing an @XmlRootElement annotation

問題は何ですか?

4

2 に答える 2

2

注: 私はEclipseLink JAXB (MOXy)のリーダーであり、JAXB (JSR-222)エキスパート グループのメンバーです。

JAXB (JSR-222) 仕様は、JSON バインディングをカバーしていません。Jettison ライブラリで JAXB 実装を使用する代わりに、ネイティブ JSON バインディングを提供する EclipseLink JAXB (MOXy) を使用できます。以下は例です。

ジャバモデル

フー

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

    private List<Bar> mylist;

}

バー

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Bar {

    private int id;
    private String name;

}

jaxb.properties

MOXy を JAXB プロバイダーとして指定するにはjaxb.properties、次のエントリを使用して、ドメイン モデルと同じパッケージで呼び出されるファイルを含める必要があります ( http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-asを参照)。 -your.html ):

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

デモコード

デモ

MOXy は@XmlRootElement注釈を必要とせず、JSON_INCLUDE_ROOTプロパティを使用して MOXy に@XmlRootElement注釈の存在を無視するように指示できます。ルート要素が無視される場合、unmarshalアンマーシャリングする型を指定するクラス パラメーターを受け取るメソッドを使用する必要があります。

import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
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[] {Foo.class}, properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource json = new StreamSource("src/forum15404528/input.json");
        Foo foo = unmarshaller.unmarshal(json, Foo.class).getValue();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(foo, System.out);
    }

}

input.json/出力

入力または出力にルート要素が存在しないことがわかります。

{
   "mylist" : [ {
      "id" : 104,
      "name" : "Only one found"
   } ]
}

追加情報

于 2013-03-14T10:29:23.257 に答える