Use Complex Type 'DateTime' for .Net Webservice through KSOAP Lib

来源:互联网 发布:数据统计app 编辑:程序博客网 时间:2024/05/14 00:59

There is a DateTime type parameter in .Net Webservice. The request should be like this:

...<soap:Body>   <TestDatetime xmlns=“...">        <oldTime>dateTime</oldTime>   </TestDatetime></soap:Body>...


If you pass a Date to the request:

  

 soapObject.addProperty("oldTime", dateObj);

There would be "cannot be serialized.." error. If you just use "dateObj.toString()". You would get "http 500" error responses.

Google it:

1.http://stackoverflow.com/questions/4004382/android-1-6-ksoap2-runtimeexception-cannot-serialize-java-util-gregoriancalen;

This way is Implementing KSOAP Marshal Interface.

I do just as what it says:

public static String testDateTime(Date oldTime){....   SoapObject rpcObj = new SoapObject(NAMESPACE, METHODNAME);    PropertyInfo parPtyInfo = new PropertyInfo();     parPtyInfo.name = "oldTime";     parPtyInfo.type = MarshalDate.DATE_CLASS;      rpcObj.addPropertyIfValue(parPtyInfo, oldTime);...}

In the MarshalDate class which implements Marshal, use "IsoDate.dateToString((Date)oldTime, IsoDate.DATE_TIME);" to complete the "writeInstance" method.

A new error occurs. It is about TimeZone.

The timezone in each side(client and server)  are GMT+08. But the result from "writeInstance" is GMT 0.

The reason is IsoDate object.

After Seeing the IsoDate code, there would be no  smog. It use Calendar with special timezone. That is it.

At the same time. We can see the result's formation is "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", so I change my own solution:

Just use SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") to format the "Date" object.

The result is OK.

Formation codes:

public static String getFullStringForWebservice(Date oldTime){     return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(oldTime);}

In the web service requestion code, just do as:

rpcObj.addProperty("oldTime", getFullStringForWebservice(oldTime));

Links:

1.http://stackoverflow.com/questions/12368631/cannot-serialize-dates-with-ksoap2;

2.http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html;

3.IsoDate code: http://wsrf4j2me.googlecode.com/svn-history/r3/trunk/wsrf4j2me/ksoap-src-latest/org/kobjects/isodate/IsoDate.java;