我在名为Attachment的JAR文件中有一个类。定义的重要部分如下。
public class Attachment
{
public List<Media> media;
public List<Media> getMedia()
{
return this.media;
}
public void setMedia(List<Media> media)
{
this.media = media;
}
}
我正在尝试使用JAXB-impl 2.1.3反序列化以下代码:
JAXBContext jaxbContext = JAXBContext.newInstance(Attachment.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(text);
Attachment attachment = (Attachment) unmarshaller.unmarshal(reader);
然而,这给了我以下错误(为了简洁而剪断)
com.sun.xml.bind.v2.runtime.IllegalAnnotationsException:
1 counts of IllegalAnnotationExceptions
Class has two properties of the same name "media"
this problem is related to the following location:
at public java.util.List com.thirdparty.Attachment.getMedia()
...
this problem is related to the following location:
at public java.util.List com.thirdparty.Attachment.media
...
我理解问题是,默认情况下,JAXB将使用PUBLIC_MEMBER的访问类型,其定义为:
除非通过XmlTransient注释,否则每个公共getter / setter对和每个公共字段都将自动绑定到XML。
所以,我的问题是,如何告诉JAXB忽略该字段并只使用getter / setter。请注意,我更喜欢这种方式,因为有许多私有字段我需要忽略(我相信附件实际上已经设置为公共错误)。
答案 0 :(得分:2)
看看Annox。它看起来有你需要的东西。
JAXB参考实现可以使用特殊的注释阅读器进行配置,该阅读器可以实现不同的阅读注释策略。 Annox利用此功能并实现了一个注释阅读器,可以从XML加载JAXB注释。
答案 1 :(得分:2)
注意:我是E clipseLink JAXB (MOXy)主管,也是JAXB (JSR-222)专家组的成员。
MOXy提供外部映射文档扩展以支持第三方类。
示例映射文档
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="blog.bindingfile">
<xml-schema
namespace="http://www.example.com/customer"
element-form-default="QUALIFIED"/>
<java-types>
<java-type name="Customer">
<xml-root-element/>
<xml-type prop-order="firstName lastName address phoneNumbers"/>
<java-attributes>
<xml-element java-attribute="firstName" name="first-name"/>
<xml-element java-attribute="lastName" name="last-name"/>
<xml-element java-attribute="phoneNumbers" name="phone-number"/>
</java-attributes>
</java-type>
<java-type name="PhoneNumber">
<java-attributes>
<xml-attribute java-attribute="type"/>
<xml-value java-attribute="number"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
从外部地图文档引导
以下是您如何创建JAXBContext
:
import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "blog/bindingfile/binding.xml");
JAXBContext jc = JAXBContext.newInstance("blog.bindingfile", Customer.class.getClassLoader() , properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(new File("src/blog/bindingfile/input.xml"));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}
}
了解更多信息