Passing JSON object from Android Client to WCF Restful service in C #

I have an android client that sends data in the form of a JSON object to my server. My server is implemented by WCF acting as a RESTful service written in C #. I have a class called "User" in my WCF and I want to perform the login action on the android client. But when I send my object in JSON format to the WCF service, I get a Null object (in the Wrapped config) or get an object whose fields are zero (in the Bare config). Does anyone have a solution for this?

Here is an example of the generated JSON by my client which:

{"User": {"username": "123", "Pass": "123", "Device": "123"}}

This is my WCF interface code:

[OperationContract] [WebInvoke(Method = "POST", UriTemplate = "Login", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json )] string Login(User user); 

And this is my App.Config:

 <system.serviceModel> <services> <service behaviorConfiguration="CityManService.TrackingBehavior" name="CityManService.Tracking"> <endpoint address="" behaviorConfiguration="json" binding="webHttpBinding" contract="CityManService.ITrackingService"> <identity> <dns value="localhost" /> </identity> </endpoint> <host> <baseAddresses> <add baseAddress="http://localhost:8731/CityManService/Tracking/" /> </baseAddresses> </host> </service> </services> <behaviors> <endpointBehaviors> <behavior name="json"> <webHttp /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="CityManService.TrackingBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> 

And finally, this is my client (android) code:

 HttpPost request = new HttpPost("http://localhost:8731/CityManService/Tracking/Login"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); // Build JSON string JSONStringer userJson = new JSONStringer() .object() .key("User") .object() .key("UserName").value(username.getText().toString()) .key("Pass").value(password.getText().toString()) .key("Device").value(password.getText().toString()) .endObject() .endObject(); StringEntity entity = new StringEntity(userJson.toString(),"UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); entity.setContentType("application/json"); request.setEntity(entity); // Send request to WCF service DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); 
+4
source share
1 answer

The wrapper name should be the name of the parameter, not the type name. In your service, an operation is defined as

 [WebInvoke(...)] string Login(User user); 

So, the input should be passed as

 {"user":{"UserName":"123","Pass":"123","Device":"123"}} 

(note the bottom username).

+4
source

Source: https://habr.com/ru/post/1383243/


All Articles