JAXB应该从`beforeMarshal(Marshaller)方法返回什么?

时间:2012-03-09 06:38:13

标签: java jaxb

首先,我不是在谈论Marshaller#Listener。 我在谈论那些class defined事件回调。

有人可以告诉我应该从boolean beforeMarshal(Marshaller)方法返回什么内容吗?

/**
 * Where is apidocs for this method?
 * What should I return for this?
 */
boolean beforeMarshal(Marshaller marshaller);

无论如何,我的意思是使用此方法将JPA's Long @Id to JAXB's String @XmlID 与JAXB-RI 转换为而不使用MOXy

[编辑] 一个void版似乎有用了。这只是一个文档问题吗?

1 个答案:

答案 0 :(得分:6)

简答

boolean返回类型是文档错误。返回类型应为void

长答案

  

我的意思是,无论如何,使用这种方法将JPA的Long @Id转换为   JAXB的String @XmlID

您可以使用EclipseLink JAXB (MOXy),因为它没有@XmlID注释的字段/属性属于String类型的限制。

  

使用JAXB-RI且没有MOXy。

您可以使用XmlAdapter来映射支持您的用例:

<强> IDAdapter

XmlAdapter会将Long值转换为String值,以满足@XmlID注释的要求。

package forum9629948;

import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class IDAdapter extends XmlAdapter<String, Long> {

    @Override
    public Long unmarshal(String string) throws Exception {
        return DatatypeConverter.parseLong(string);
    }

    @Override
    public String marshal(Long value) throws Exception {
        return DatatypeConverter.printLong(value);
    }

}

<强>乙

@XmlJavaTypeAdapter注释用于指定XmlAdapter

package forum9629948;

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlAccessorType(XmlAccessType.FIELD)
public class B {

    @XmlAttribute
    @XmlID
    @XmlJavaTypeAdapter(IDAdapter.class)
    private Long id;

}

<强> A

package forum9629948;

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class A {

    private B b;
    private C c;

}

<强> C

package forum9629948;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)public class C {

    @XmlAttribute
    @XmlIDREF
    private B b;

}

<强>演示

package forum9629948;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(A.class);

        File xml = new File("src/forum9629948/input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        A a = (A) unmarshaller.unmarshal(xml);

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

}

<强>输入/输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a>
    <b id="123"/>
    <c b="123"/>
</a>