【发布时间】:2012-07-02 07:56:26
【问题描述】:
也许该方法正在返回它应该返回的方式,但我基本上只是做了一个看起来像这样的测试方法
[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());
....
}
...
【问题讨论】:
-
你是如何从 android 调用这个的?您是否在该请求中指定了任何内容类型?
-
我不是,但我只是尝试添加 httpGet.setHeader("Content-Type", "application/json");当我添加这个 web 服务返回 500 服务器错误状态代码。我将更新我的问题以包含我用来调用 Web 服务方法的 android 代码
-
看起来其他人遇到了类似的问题,我在我的广泛研究(5 分钟谷歌搜索)期间错过了类似的问题stackoverflow.com/questions/2058454/… ...显然,如果我使用 POST 而不是获取内容,它会起作用类型设置为 application/json
标签: android asp.net xml json web-services