gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:18:01 26 4
gpt4 key购买 nike

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

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

最佳答案

关于android - 创建一个返回 JSON 而不是 XML 的 ASP.net WebService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11284584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com