加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 03:00:00 所属栏目:Java 来源:网络整理
导读:首先,我不是在谈论 Marshaller#Listener. 我在谈论那些类定义的事件回调. 任何人都可以告诉我应该从boolean beforeMarshal(Marshaller)方法返回什么? /** * Where is apidocs for this method? * What should I return for this? */boolean beforeMarshal(M
首先,我不是在谈论 Marshaller#Listener.
我在谈论那些类定义的事件回调.

任何人都可以告诉我应该从boolean beforeMarshal(Marshaller)方法返回什么?

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

无论如何,我的意思是使用此方法将JPA的Long @Id转换为JAXB的String @XmlID,使用JAXB-RI并且不使用MOXy.

[编辑]
一个虚空版本似乎工作.这只是一个文档问题吗?

解决方法

简答

布尔返回类型是文档错误.返回类型应该是无效的.

答案很长

I mean,anyway,to use this method for converting JPA’s Long @Id to
JAXB’s String @XmlID

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

with JAXB-RI and without 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;

}

一个

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读