android – Send an object using Gson


I have the following problem: I need to send an object to my web-service, however, it is not feasible to use JSONStringer, as my class has many fields. What would be the best way to solve this problem? I used the following method, but it didn't work (it returns that my object is null), the code follows:

 public String postPedido( Pedido pedido) 
        int statusCode = 400;

            HttpPost request = new HttpPost(SVC_URL );
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");

           Gson gson = new Gson();

           String json = gson.toJson(pedido, Pedido.class);
           StringEntity entity = new StringEntity(json);


            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(request);

            statusCode = response.getStatusLine().getStatusCode();


        catch (Exception e) 


        return String.valueOf(statusCode);

Here is the signature of the Web Service method:

        Method = "POST",
        UriTemplate = "PostPedido",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    bool PostPedido(Pedido pedido);

And the method is this:

public bool PostPedido(Pedido pedido)
        var teste = new StringBuilder();
        bool result = false;
        if (pedido != null)
            teste.AppendLine(String.Format("Numero do pedido {0}", pedido.NumeroOrcamento));
            teste.AppendLine(String.Format("Total Pedido {0}", pedido.TotalPedido));
            result = true;
            teste.AppendLine("pedido vazio");
            result = false;
        System.IO.File.WriteAllText(@"c:\teste.txt", teste.ToString());

        return result;

PS: For now, this method is for testing purposes only.


Change the BodyStyle property of the PostRequest method's WebInvoke attribute in the contract to:

BodyStyle = WebMessageBodyStyle.WrappedResponse
Scroll to Top