2012-10-16 58 views
2

我的Android客戶端試圖將JSON類發佈到我的wcf服務時出現問題。 下面是Android客戶端的代碼:爲WCFAndroid JSON發佈到WCF服務

[OperationContract] 
    [WebInvoke(Method = "POST", 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Wrapped, 
     UriTemplate = "TestPost")] 
    void TestPost(TestModel tm); 





[DataContract] 
public class TestModel 
{ 
    [DataMember(Name = "p1")] 
    public string p1 { get; set; } 

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

    [DataMember(Name = "p3")] 
    public int p3 { get; set; } 

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

    [DataMember(Name = "p5")] 
    public int p5 { get; set; } 

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

}

在我的WCF方法的參數TestModel TM總是空

public HttpResponse TestPost() throws Exception 
{ 

    HttpPost httpost = new HttpPost(url+"/TestPost"); 

    JSONStringer img = new JSONStringer() 
     .object() 
     .key("TestModel") 
      .object() 
       .key("p1").value("test") 
       .key("p2").value("test") 
       .key("p3").value(1) 
       .key("p4").value("test") 
       .key("p5").value(2) 
       .key("p6").value("test;test") 
      .endObject() 
     .endObject(); 
     StringEntity se = new StringEntity(img.toString()); 

    httpost.setEntity(se); 

    httpost.setHeader("Accept", "application/json"); 
    httpost.setHeader("Content-type", "application/json"); 

    return httpclient.execute(httpost); 
} 

這裏是代碼。什麼可能是錯的?

+1

你檢查了生成的json嗎? – toadzky

+0

Yepp,它正在生成。 – Krika

回答

3

對象的包裝(自從您指定WebMessageBodyStyle.Wrapped)是基於參數名稱而不是參數類型完成的。最外面的JSON成員的名稱應該是「tm」,而不是「TestModel」:

public HttpResponse TestPost() throws Exception 
{ 
    HttpPost httpost = new HttpPost(url+"/TestPost"); 

    JSONStringer img = new JSONStringer() 
     .object() 
     .key("tm") 
      .object() 
       .key("p1").value("test") 
       .key("p2").value("test") 
       .key("p3").value(1) 
       .key("p4").value("test") 
       .key("p5").value(2) 
       .key("p6").value("test;test") 
      .endObject() 
     .endObject(); 
     StringEntity se = new StringEntity(img.toString()); 

    httpost.setEntity(se); 

    httpost.setHeader("Accept", "application/json"); 
    httpost.setHeader("Content-type", "application/json"); 

    return httpclient.execute(httpost); 
} 
+0

謝謝,錯過了:)。我還需要將內容類型和內容編碼設置爲UTF-8才能讓我工作。 StringEntity entity = new StringEntity(json.toString()); entity.setContentType( 「應用程序/ JSON;字符集= UTF-8」); (新的BasicHeader(HTTP.CONTENT_TYPE,「application/json; charset = UTF-8」)); httpost.setEntity(entity); – Krika