2012-07-01 79 views
6

也許該方法返回它應該如何,但我基本上只是做了一個測試方法,看起來像這樣創建ASP.net WebService的返回而不是XML JSON

[WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string TestJSON() 
    { 
     var location = new Location[2]; 
     location[0] = new Location(); 
     location[0].Latitute = "19"; 
     location[0].Longitude = "27"; 
     location[1] = new Location(); 
     location[1].Latitute = "-81.9"; 
     location[1].Longitude = "28"; 

     return new JavaScriptSerializer().Serialize(location); 
    } 

當我打這個從我的android應用程序我得到這樣

Value <?xml of type java.lang.String cannot be converted to JSONArray 

我覺得這個方法將返回只是直JSON異常,但是這是Web服務方法返回

<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">[{"Latitute":"19","Longitude":"27"},{"Latitute":"-81.9","Longitude":"28"}]</string> 

是不是應該這樣?有沒有辦法刪除JSON之外的XML內容?我不知道我有我的web服務做,使其返回數據

代碼在Android上使用來調用web服務

public String readWebService(String method) 
{ 
    StringBuilder builder = new StringBuilder(); 
    HttpClient client = new DefaultHttpClient(); 
    HttpGet httpGet = new HttpGet("http://myserver.com/WebService.asmx/" + method); 


    Log.d(main.class.toString(), "Created HttpGet Request object"); 

    try 
    { 
     HttpResponse response = client.execute(httpGet); 
     Log.d(main.class.toString(), "Created HTTPResponse object"); 
     StatusLine statusLine = response.getStatusLine(); 
     Log.d(main.class.toString(), "Got Status Line"); 
     int statusCode = statusLine.getStatusCode(); 
     if (statusCode == 200) { 
      HttpEntity entity = response.getEntity(); 
      InputStream content = entity.getContent(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       builder.append(line); 
      } 

      return builder.toString(); 
     } else { 
      Log.e(main.class.toString(), "Failed to contact Web Service: Status Code: " + statusCode); 
     } 
    } 
    catch (ClientProtocolException e) { 
     Log.e(main.class.toString(), "ClientProtocolException hit"); 
     e.printStackTrace(); 
    } 
    catch (IOException e) { 
     Log.e(main.class.toString(), "IOException hit"); 
     e.printStackTrace(); 
    } 
    catch (Exception e) { 
     Log.e(main.class.toString(), "General Exception hit"); 
    } 

    return "WebService call failed";  
} 

那麼正確的格式我的地方調用這個方法在代碼如

try { 
    JSONArray jsonArray = new JSONArray(readWebService("TestJSON")); 
    Log.i(main.class.toString(), "Number of entries " + jsonArray.length()); 
     .... 
} 
... 
+0

你是怎麼從android調用它的?您是否在該請求中指定了任何內容類型? –

+0

我不是,但我只是嘗試添加httpGet.setHeader(「Content-Type」,「application/json」);當我添加這個web服務返回一個500服務器錯誤狀態代碼。我會更新我的問題,包括我用來調用Web服務方法的Android代碼 –

+0

看起來像別人有類似的問題,我在我的廣泛研究(5分鐘谷歌搜索)中錯過了http://stackoverflow.com/questions/2058454/asp-net-webservice-is-wrapping-my-json-reponse -with-xml-tags?rq = 1 ...顯然,如果我使用POST而不是get的內容類型設置到application/json –

回答

相關問題