也许这个方法正在返回它应该如何返回,但我基本上只是做了一个测试方法,如下所示

    [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内容?我不确定在我的webservice中要做什么才能使它返回正确的数据格式
android上调用webservice的代码
   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());
        ....
}
...

最佳答案

试试这个代码。它会帮你的。
http://www.codeproject.com/Articles/45275/Create-a-JSON-WebService-in-ASP-NET-2-0-with-a-jQu

07-24 09:43
查看更多