2012-07-01 51 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 –

回答

相关问题