JAXB: @XmlTransient on third-party or external sup

2019-02-14 05:44发布

I need some help regarding the following issue with JAXB 2.1.

Sample: I've created a SpecialPerson class that extends a abstract class Person. Now I want to transform my object structure into a XML schema using JAXB. Thereby I don't want the Person XML type to appear in my XML schema to keep the schema simple. Instead I want the fields of the Person class to appear in the SpecialPerson XML type.

Normally I would add the annotation @XmlTransient on class level into the Person code.

The problem is that Person is a third-party class and I have no possibility to add @XmlTransient here. How can I tell JAXB that it should ignore the Person class without annotating the class. Is it possible to configure this externally somehow?

Have you had the same problem before? Any ideas what the best solution for this problem would be?

5条回答
Summer. ? 凉城
2楼-- · 2019-02-14 06:09

The EclipseLink JAXB (MOXy) implementation offers a means of representing the metadata as XML that you could use:

You can specify some of the metadata using annotations, and the rest as XML. Below is what your document would look like:

<xml-bindings xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm">

    <java-types>

        <java-type name="Person" xml-transient="true"/>

    </java-types>

</xml-bindings>

查看更多
beautiful°
3楼-- · 2019-02-14 06:14

OK, this was a pain in the you-know-what. Finally, after sifting through many a blog postings, here's what I did,

added a package-info.java class in the 'third-party class' package like this,

@javax.xml.bind.annotation.XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.NONE) package third-party-package;

In my case, it was just one package so it was easy. Obviously, you will have to do this for for every separate package structure. I haven't tried doing it at a master package level.

查看更多
三岁会撩人
4楼-- · 2019-02-14 06:23

You can annotate your SuperPerson class with @XmlTransient, that will instruct JaxB not to automatically marshal all properties. And then annotate each getter (or field) you want to serialize with the relevant annotation.

This approach is not very elegant, but it should work

查看更多
够拽才男人
5楼-- · 2019-02-14 06:24

I posted another solution with complete code here

JAXB External Custom Binding XJC Issue - Parsing results in empty node

in case you are interested.

查看更多
戒情不戒烟
6楼-- · 2019-02-14 06:28

You can provide mappings for third-party classes using Annox.

查看更多
登录 后发表回答