简体   繁体   中英

Unmarshaling an element of type Number with JAXB

hello i'm using JAXB to unmarshal XML to JAVA, i have an element "value" in my xml document that could be of type int, or double, and the corresponding attribute of this element in my java class is "value" of type Number.

JAXB does not support umarshaling for "Number" type i think, does anybody have an idea how to handle this problem ? an example is going to be really appreciated. thanks in advance.

Write adapter, for example:

import java.math.BigDecimal;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class NumberAdapter extends XmlAdapter<String, Number> {

    @Override
    public Number unmarshal(String v) throws Exception {
        return new BigDecimal(v);
    }

    @Override
    public String marshal(Number v) throws Exception {
        return v.toString();
    }

}

and use it with variable declaration:

@XmlJavaTypeAdapter(NumberAdapter.class)
private Number myNumber;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM