3
I have the following problem: I need to send an object to my web-service, but 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 didn’t work (returns that my object is null), 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);
}
Follow the signature of the Web Service method:
[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: For now, this method is only for testing.
What exactly is your null object you refer to? A string
json
? Theentity
? If this is the case, try to inform charset in the second parameter.– Paulo Rodrigues
The object is recognized as null by the web-service.
– Fabio Calefi
Fabio, welcome to [en.so]! There doesn’t seem to be anything wrong with your code, but it can be a problem or incompatibility with the web service. The ideal would be to recover the raw log of how the request arrives on the server to determine if it is arriving in exactly the expected format. You can post the method used in the web service?
– utluiz
I edited the question, adding the method used in the Web Service.
– Fabio Calefi