Search code examples
javajaxbunmarshallingjaxb2

Java Jaxb unmarshall and endianness of data


I am planning to use jaxb to unmarshall xml in to POJO. Now this pojo will be serialized and sent over network to some other application. Now some of this POJO contains a int field (4 or 8 bytes) which when read from xml need to be serialized in either little endian or big endian notation based on some flag. (this flag is not field by field but rather at application instance level). Is there anyway In Jaxb while unmarshalling can honor this endianness setting by some sort of annotation in xml?

Any help in this regards is appreciated.

Thanks


Solution

  • You can specify your own XmlAdapter in your POJO:

    @XmlElement(name="intField")
    @XmlJavaTypeAdapter(EndianIntAdapter.class)
    public int intField;
    

    And then implement the adapter:

    class EndianIntAdapter extends XmlAdapter<String, Integer> {
      @Override
      public String marshal(Integer field) throws Exception {
        //int to string based on endianness
      }
    
      @Override
      public Integer unmarshal(String str) throws Exception {
        //String from xml to int based on endianness
      }
    }