创建一个返回JSON而不是XML的ASP.net WebService

时间:2012-07-01 18:26:44

标签: android asp.net xml json web-services

也许该方法正在返回它应该如何,但我基本上只是制作了一个看起来像这样的测试方法

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

1 个答案:

答案 0 :(得分:2)