gpt4 book ai didi

c# - 将 JSON 对象从 Android 客户端传递到 C# 中的 WCF Restful 服务

转载 作者:太空狗 更新时间:2023-10-30 01:24:51 24 4
gpt4 key购买 nike

我有一个 android 客户端,它以 JSON 对象形式将数据发送到我的服务器。我的服务器由 WCF 实现,充当用 C# 编写的 RESTful 服务。我的 WCF 中有一个名为“用户”的类,我想在 android 客户端中执行登录操作。但是当我以 JSON 格式将我的对象发布到 WCF 服务时,我得到一个 Null 对象(在 Wrapped 配置中)或者我得到一个字段为 null 的对象(在 Bare 配置中)。有人对此有解决方案吗?

这是我的客户生成的 JSON 示例:

{"用户":{"用户名":"123","密码":"123","设备":"123"}}

这是我的 WCF 接口(interface)代码:

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

最佳答案

包装器的名称应该是参数 名称,而不是类型 名称。在您的服务中,操作定义为

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

所以输入应该作为

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

(注意小写的“用户”对象名称)。

关于c# - 将 JSON 对象从 Android 客户端传递到 C# 中的 WCF Restful 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8281985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com