2012-07-01 26 views
6

Tal vez el método está volviendo la forma en que debería, pero básicamente sólo hice un método de prueba que tiene este aspectoLa creación de un servicio Web ASP.net que devuelve JSON en lugar de XML

[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); 
    } 

cuando golpeo esto desde mi androide aplicación consigo una excepción como ésta

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

pensé que este método podría volver JSON sólo directamente, pero esto es lo que devuelve el método de servicio web

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

¿Se supone que debe ser así? ¿Hay alguna manera de eliminar las cosas XML que están fuera de JSON? No estoy seguro de lo que tengo que hacer en mi servicio web para hacerla regresar el formato correcto de los datos

código utilizando en Android llamar al servicio 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";  
} 

entonces yo llamaría ese método en algún lugar del código como

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

Cómo estás llamando esto desde Android? ¿Estás especificando cualquier tipo de contenido en esa solicitud? –

+0

No lo estaba pero intenté agregar httpGet.setHeader ("Content-Type", "application/json"); cuando agrego esto, el servicio web devuelve un código de estado de error de 500 servidores. Actualizaré mi pregunta para incluir el código de Android que estoy usando para llamar al método de servicio web –

+0

Parece que alguien más tenía un problema similar que me perdí durante mi extensa investigación (5 minutos de búsqueda en Google) http://stackoverflow.com/questions/2058454/asp-net-webservice-is-wrapping-my-json-reponse-with-xml-tags? rq = 1 ... aparentemente funciona si uso un POST en lugar de un get con el tipo de contenido establecido a la aplicación/json –

Respuesta

Cuestiones relacionadas