Showing posts with label marshal. Show all posts
Showing posts with label marshal. Show all posts

Implementing KSOAP Marshal Interface



Another poorly documented spot in KSOAP: marshaling arguments. In KSOAP, you need to implement an interface called Marshal so that the XML parser would know how to serialize and deserialize objects you are trying to pass through the web service.

Strangely enough, object types like "double" and "Date" need to be manually marshaled! This is why I decided my code examples to show how to marshal dates and doubles. So here it goes:

package Marshals;

import java.io.IOException;

import org.ksoap2.serialization.Marshal;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
/**
* 
* @author Vladimir
* Used to marshal Doubles - crucial to serialization for SOAP
*/
public class MarshalDouble implements Marshal 
{


    public Object readInstance(XmlPullParser parser, String namespace, String name, 
            PropertyInfo expected) throws IOException, XmlPullParserException {
        
        return Double.parseDouble(parser.nextText());
    }


    public void register(SoapSerializationEnvelope cm) {
         cm.addMapping(cm.xsd, "double", Double.class, this);
        
    }


    public void writeInstance(XmlSerializer writer, Object obj) throws IOException {
           writer.text(obj.toString());
        }
    
}