Send an object using Gson

3

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

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

            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);


           request.setEntity(entity);

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

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

        } 

        catch (Exception e) 
        {
            e.printStackTrace();

        }

        return String.valueOf(statusCode);
    }

The Web Service method signature follows:

[OperationContract]
    [WebInvoke(
        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;
        }
        else
        {
            teste.AppendLine("pedido vazio");
            result = false;
        }
        System.IO.File.WriteAllText(@"c:\teste.txt", teste.ToString());

        return result;
    } 

PS: This method is for testing purposes only.

    
asked by anonymous 07.04.2015 / 13:28

1 answer

1

Change the BodyStyle property of the WebInvoke attribute of the Request method in the contract to:

BodyStyle = WebMessageBodyStyle.WrappedResponse
    
08.04.2015 / 17:15