あなたのモデルはそのまま私のために働きます。以下の例を参照してください。
デモ
package forum13350129;
import java.util.*;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Quiz.class);
Question question1 = new Question();
List<Answer> answers1 = new ArrayList();
answers1.add(new Answer());
answers1.add(new Answer());
question1.setAnswers(answers1);
Question question2 = new Question();
List<Answer> answers2 = new ArrayList();
answers2.add(new Answer());
answers2.add(new Answer());
question2.setAnswers(answers2);
Quiz quiz = new Quiz();
quiz.getQuestions().add(question1);
quiz.getQuestions().add(question2);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(quiz, System.out);
}
}
出力
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<quiz>
<questions>
<answers/>
<answers/>
</questions>
<questions>
<answers/>
<answers/>
</questions>
</quiz>
更新 #1
私のように JSON として取得しようとするとどうなりますか?
これは依存します。JSON バインディングはJAXB (JSR-222)仕様の一部ではありません。これは、環境が次のいずれかを実行していることを意味します。
- Jettison などのライブラリで JAXB impl を使用して JSON を生成する (参照: http://blog.bdoughan.com/2011/04/jaxb-and-json-via-jettison.html )
- JSON バインディング ライブラリ (JAXB アノテーションをサポートする Jackson など) を使用する
- JSON バインディングを提供する EclipseLink MOXy などの JAXB impl を使用する ( http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.htmlを参照)。
次のようにEclipseLink JAXB (MOXy)を使用します。
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.marshal(quiz, System.out);
次の JSON が生成されます。
{
"quiz" : {
"questions" : [ {
"answers" : [ {
}, {
} ]
}, {
"answers" : [ {
}, {
} ]
} ]
}
}
更新 #2
遅延読み込み関係の問題を修正しました。リポジトリで Hibernate.initialize を使用しています。私が持っているリソースからこのクイズ オブジェクトを返そうとしています。私はJAX-RSを使用しています。
Hibernate モデルを XML にマーシャリングする際に問題を抱えている人を見てきました。この問題は、Hibernate が使用するプロキシ オブジェクトが原因だったと思います。以下のリンクで、 を使用しXmlAdapter
てプロキシ オブジェクトと実際のオブジェクトを変換することを提案しましたが、これは役に立ちました。