Java HTML / XML How to - Convert yes/no during Jaxb unmarshalling








Question

We would like to know how to convert yes/no during Jaxb unmarshalling.

Answer

/*from ww w  .  j av a 2s .c  om*/
import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

public class Main {

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

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Root root = (Root) unmarshaller.unmarshal(new File(
        "input.xml"));

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

  @XmlRootElement
  public static class Root {

    @XmlAttribute
    @XmlJavaTypeAdapter(BooleanAdapter.class)
    private Boolean a;

    public boolean isA() {
      return a;
    }

    public void setA(String s) {
      this.a = "yes".equals(s) || "on".equals(s) || "in".equals(s);
    }

  }

  public static class BooleanAdapter extends XmlAdapter<String, Boolean> {

    @Override
    public Boolean unmarshal(String s) throws Exception {
      return "yes".equals(s) || "on".equals(s) || "in".equals(s);
    }

    @Override
    public String marshal(Boolean b) throws Exception {
      if (b) {
        return "yes";
      }
      return "no";
    }

  }
}

input.xml

<?xml version="1.0" encoding="UTF-8"?>
<root a="on"/>