反序列化从Android应用程序发送到WCF Web服务的JSON对象

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

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

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

android应用程序的代码:

 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

                                    <!---->   <!-- -->     

@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; } } }