Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass complex types like objects using Webservices?

This may sound like a simple question but as am newbie in Webservies and this is my first time using it and so am asking my doubt.

Q: How can I pass objects or complex types using Web Services ? I have created a simple webservice and am passing string and integer types but I am not sure how can I pass objects using webservice and so any guidance would be highly appreciated.

Thanks.

like image 520
Rachel Avatar asked Sep 10 '10 15:09

Rachel


2 Answers

You only have to serialize the object (make a text) on the service-side and de-serialze (make an object again) on the receiver-side. For years SOAP was standard for this, but today JSON becomes more popular as it has lot less overhead than SOAP.

If using SOAP and Java you may try GSON by Google, which provides a very easy-to-use programming interface.

JSON with GSON:

String jsonized = new Gson().toJson( myComplexObject ); 
/* no we have a serialized version of myComplexObject */ 

myComplexObjectClass myComplexObjext = new Gson().fromJson( jsonized, myComplexObjectClass.class ); 
/* now we have the object again */

For JSON with JAX-WS (we don't use Apache Axis) have a look at these starter-tutorials:

  • http://myarch.com/create-jax-ws-service-in-5-minutes
  • http://www.myeclipseide.com/documentation/quickstarts/webservices_jaxws/
like image 177
heb Avatar answered Sep 23 '22 20:09

heb


If you are using restful web services (I'd recommend Jersey if you are http://jersey.dev.java.net) you can pass JAXB annotated objects. Jersey will automatically serialize and deserialize your objects on both the client and server side.

Server side;

@Path("/mypath")
public class MyResource
{
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public MyBean getBean()
    {
        MyBean bean = new MyBean();
        bean.setName("Hello");
        bean.setMessage("World");
        return bean;
    }

    @POST
    @Consumers(MediaType.APPLICATION_XML)
    public void updateBean(MyBean bean)
    {
        //Do something with your bean here
    }
}

Client side;

//Get data from the server
Client client = Client.create();
WebResource resource = client.resource(url);
MyBean bean = resource.get(MyBean.class);

//Post data to the server
bean.setName("Greetings");
bean.setMessage("Universe");
resource.type(MediaType.APPLICATION_XML).post(bean);

JAXB bean;

@XmlRootElement
public class MyBean
{
    private String name;
    private String message;

    //Constructors and getters/setters here
}
like image 22
Qwerky Avatar answered Sep 19 '22 20:09

Qwerky