【问题标题】:Deserialize JSON object sent from Android app to WCF webservice反序列化从 Android 应用程序发送到 WCF Web 服务的 JSON 对象
【发布时间】:2012-10-31 18:43:02
【问题描述】:

我正在尝试向我的 webservice 方法发送一个 JSON 对象,该方法的定义如下:

public String SendTransaction(string trans)
{
            var json_serializer = new JavaScriptSerializer();
            Transaction transObj = json_serializer.Deserialize<Transaction>(trans);
            return transObj.FileName;       
}

我想在哪里返回我作为参数获得的这个 JSON 字符串的 FileName。

安卓应用的代码:

HttpPost request = new HttpPost(
                "http://10.118.18.88:8080/Service.svc/SendTransaction");
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");

        // Build JSON string
        JSONStringer jsonString;

        jsonString = new JSONStringer()
                .object().key("imei").value("2323232323").key("filename")
                .value("Finger.NST").endObject();

        Log.i("JSON STRING: ", jsonString.toString());

        StringEntity entity;

        entity = new StringEntity(jsonString.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);
        HttpEntity httpEntity = response.getEntity();
        String xml = EntityUtils.toString(httpEntity);

        Log.i("Response: ", xml);
        Log.d("WebInvoke", "Status : " + response.getStatusLine());

我只得到一个很长的 html 文件,它告诉我 The server has encountered an error processing the request。并且状态码是HTTP/1.1 400 Bad Request

我的 Transaction 类在 C# 中是这样定义的:

 [DataContract]
public class Transaction
{
    [DataMember(Name ="imei")]
    public string Imei { get; set; }

    [DataMember (Name="filename")]
    public string FileName { get; set; }
}

我怎样才能以正确的方式做到这一点?

编辑,这是我的 web.config

 <?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>

          <endpointBehaviors>
            <behavior name="httpBehavior">
                <webHttp />
            </behavior >
        </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
    <services>
      <service name="Service.Service">
        <endpoint address="" behaviorConfiguration="httpBehavior" binding="webHttpBinding" contract="Service.IService"/>
      </service>
    </services>

    <protocolMapping>
        <add binding="webHttpBinding" scheme="http" />
    </protocolMapping>

    <!--<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />-->
  </system.serviceModel>
  <system.webServer>
  <!-- <modules runAllManagedModulesForAllRequests="true"/>-->
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

【问题讨论】:

  • 我的猜测:这与您的服务配置有关
  • 你能看看我的编辑吗?
  • 嗯,我一直很难阅读配置文件。你试过像[OperationContract] [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] public String SendTransaction(string trans) { }这样装饰你的方法吗
  • 是的,我就是这么做的。
  • 我也会尝试更改您的方法,因为public String SendTransaction(Transaction transObj) { return transObj.FileName; } 反序列化应该由 WCF 处理。

标签: c# android wcf


【解决方案1】:

@Tobias,这不是答案。但由于评论有点长,我把它贴在这里。也许它可以帮助诊断您的问题。 [完整的工作代码]。

public void TestWCFService()
{
    //Start Server
    Task.Factory.StartNew(
        (_) =>{
            Uri baseAddress = new Uri("http://localhost:8080/Test");
            WebServiceHost host = new WebServiceHost(typeof(TestService), baseAddress);
            host.Open();
        },null,TaskCreationOptions.LongRunning).Wait();


    //Client
    var jsonString = new JavaScriptSerializer().Serialize(new { xaction = new { Imei = "121212", FileName = "Finger.NST" } });
    WebClient wc = new WebClient();
    wc.Headers.Add("Content-Type", "application/json");
    var result = wc.UploadString("http://localhost:8080/Test/Hello", jsonString);
}

[ServiceContract]
public class TestService
{
    [OperationContract]
    [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    public User Hello(Transaction xaction)
    {
        return new User() { Id = 1, Name = "Joe", Xaction = xaction };
    }

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Transaction Xaction { get; set; }
    }

    public class Transaction
    {
        public string Imei { get; set; }
        public string FileName { get; set; }
    }
}

【讨论】:

  • 你在 wcf 服务中哪里定义你的UriTemplate?为了从浏览器访问它,我认为 web 服务中的每个方法都必须定义它。其次,您使用的是什么类型的方法? PUT, POST, GET ?
  • @TobiasMoeThorstensen UriTemplate 是可选的。如果您想使用默认 uri 以外的另一个 uri(即方法名),则为必需。 UploadString 方法使用 POSTDownloadString 使用GETWebInvoke 属性定义为 POST,WebGet 为 GET)
  • 我终于更进一步了,我实际上得到了我的webservice的响应,但是服务返回的Transaction对象是null我怀疑这与客户端有关一边。
  • 现在可以正常工作了,来自 java 的 JSON 对象中的 Keys 必须与 DataContract 中的 Datamembers 的名称相同,然后我删除了 BodyStyle = WebMessageBodyStyle.Wrapped来自WebInvoke 声明。我会接受你的回答,因为它让我知道从哪里开始!谢谢
猜你喜欢
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多