我有一个android客户端,它以JSON对象形式将数据发送到我的服务器。我的服务器由WCF实现,充当用C#编写的RESTful服务。我有一个名为" User"在我的WCF中,我想在Android客户端中执行登录操作。但是当我以JSON格式将对象发布到WCF服务时,我得到一个Null对象(在Wrapped配置中)或者我得到一个字段为空的对象(在Bare配置中)。有人有解决方案吗?
以下是我的客户生成的JSON示例:
{"用户" {"用户名":" 123""通行证":" 123&#34 ;, "装置":" 123"}}
这是我的WCF接口代码:
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "Login",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json
)]
string Login(User user);
这是我的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>
最后这是我的客户端(android)代码:
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);
答案 0 :(得分:4)
包装器的名称应该是参数名称,而不是类型名称。在您的服务中,操作定义为
[WebInvoke(...)]
string Login(User user);
因此输入应该作为
传递{"user":{"UserName":"123","Pass":"123","Device":"123"}}
(注意小写的“用户”对象名称)。