也许该方法正在返回它应该返回的方式,但我基本上只是做了一个看起来像这样的测试方法
[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 内容?我不确定我必须在我的网络服务中做什么才能使其返回正确的数据格式
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());
....
}
...