How to serialize java.sql.Date as Long, when using

2019-05-27 06:42发布

问题:

I have a simple web service method that returns a simple java class as return value.

@WebMethod()
public SimpleClass myMethod();

@XmlRootElement()
public class SimpleClass {
    @XmlElement(name="myDate")
    @XmlJavaTypeAdapter(value=MyDateAdapter.class)
    public java.sql.Date myDate = new java.sql.Date(new java.util.Date().getTime());
}

I want that java.sql.Date will transmitted as Long value in the XML (because the client is J2ME that cannot handle complex things). For this puprpose I took the solution that was mentioned in many places before, and worked great on Glassfish v2.

First, I declare the following adapter:

 public class MyDateAdapter extends XmlAdapter<Long, java.sql.Date> {
     public java.sql.Date unmarshal(Long v) throws Exception {
        return new java.sql.Date(v);
     }
     public Long marshal(java.sql.Date v) throws Exception {
         return v.getTime();
     }
 }

Then, I declare its usage in package-info file like this:

 @XmlJavaTypeAdapters({
    @XmlJavaTypeAdapter(value=MyDateAdapter.class,type=java.sql.Date.class)
 })
 package mingler.tracker.ejb.client;

The problem happens on GlassFish 3. The date is transmitted as "xs:dateTime" value, instead of Long, although I defined the adapter properly. This is the response I get from GlassFish 3 server, when I call my web service:

<?xml version="1.0" encoding="UTF-8"?>
 <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
     <S:Body>
         <ns2:myMethodResponse xmlns:ns2="http://nevermind.com">
             <return>
                 <myDate xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:dateTime">2010-12-09T12:44:06.875+02:00</myDate>
             </return>
         </ns2:myMethodResponse>
     </S:Body>
 </S:Envelope>

I also checked with the debugger -- the functions in the adapter are never called. On the other hand, the adapater is not useless, because if I try to remove it I get JAXB exception, telling me that java.sql.Date cannot be handled because it doesn't have no-arg constructor.

Any ideas?

20/12/2010 - I added links to a project jar with sources and the results for glassfish2 and glassfish3:
jar file ,glassfish3 result , glassfish2 result

回答1:

I have posted a bug for this issue, it should be solved on version 3.1 (link)



回答2:

You have the @XmlJavaTypeAdapter declared at both the property level and the package level. Have you tried only declaring it in one spot?

Either:

@XmlJavaTypeAdapter(value=MyDateAdapter.class)
public java.sql.Date myDate = new java.sql.Date(new java.util.Date().getTime());

Or:

 @XmlJavaTypeAdapters({
    @XmlJavaTypeAdapter(value=MyDateAdapter.class,type=java.sql.Date.class)
 })
 package mingler.tracker.ejb.client;

Instead of both.