JAXB unmarshalling Custom entities without annotat

2019-01-28 04:19发布

问题:

We have an xml file which we need to unmarshall(convert into a Java Object). Now the Java object is of third party and I cannot annotate it for unmarshalling. Any idea as to how I can Unmarshal without annotation. Please find my code snippet below

JAXBContext context;
        try {
            context = JAXBContext.newInstance(Abc.class);
            Unmarshaller unMarshaller = context.createUnmarshaller();
            Abc abc= (Abc) unMarshaller.unmarshal(new FileInputStream("C:\\Documents and Settings\\sandeep.nair\\Desktop\\abc.xml"));
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (Exception e){

        }

I am getting the following exception. One for No argument Constructor(I know I can solve this by adding annotation for Adapter but I want to know or see a sample snippet for handling it without annotation)

Similarly I am getting another message as to Interfaces cannot be handle by JAXB.

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 5 counts of IllegalAnnotationExceptions java.sql.Timestamp does not have a no-arg default constructor. this problem is related to the following location: at java.sql.Timestamp at public java.sql.Timestamp com.test.Abc.getSomeTimestamp() at com.riteaid.entities.customer.Customer com.test.Def does not have a no-arg default constructor. this problem is related to the following location: at com.test.Def...

java.sql.Date does not have a no-arg default constructor. this problem is related to the following location: at java.sql.Date ... com.test.Ghi is an interface, and JAXB can't handle interfaces. this problem is related to the following location: ... com.test.Ghi does not have a no-arg default constructor. this problem is related to the following location: ..

回答1:

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

JAXB is configuration by exception , so you only need to add annotations where you want to override the default mapping behaviour:

  • http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html

The standard way of supplying metadata is through annotations. In situations where you can't annotate such as 3rd party classes, then you may be interested in MOXy's external mapping document extension.

  • http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html
  • http://blog.bdoughan.com/2012/04/extending-jaxb-representing-metadata-as.html

You can use an XmlAdapter to handle the javax.sql.Date and javax.sql.Timestamp types:

  • jaxb unmarshal timestamp