我實現了一個Web服務,它返回一個JSON字符串返回如下:錯誤解析JSONArray從.NET Web服務
{"checkrecord":[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}
在我的Android應用我試圖解析字符串轉換爲JSONArray,但我無法這樣做,因爲我在logcat中遇到以下異常:
11-16 22:15:57.381: ERROR/log_tag(462): Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray
如何解決這個問題?
我的Android代碼如下:
public static JSONArray getJSONfromURL(String b)
{
//initialize
InputStream is = null;
String result = "";
JSONArray jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//try parse the string to a JSON array
try{
jArray = new JSONArray(result);
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
這是Web服務代碼,返回JSON
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public String getdata(String rollno)
{
String json;
try
{
using (SqlConnection myConnection = new SqlConnection(@"Data Source=\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123"))
{
string select = "select * from checkrecord where rollno=\'" + rollno + "\'";
SqlDataAdapter da = new SqlDataAdapter(select, myConnection);
DataSet ds = new DataSet();
da.Fill(ds, "checkrecord");
DataTable dt = new DataTable();
ds.Tables.Add(dt);
json = Newtonsoft.Json.JsonConvert.SerializeObject(ds);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
return json;
}
您返回的字符串中包含的事實 '<?xml的' 告訴我您的Web服務正在返回XML而不是您指定的JSON。確保您提供的網址實際上返回了JSON。 –
它只返回json,我發佈了我的web服務代碼 –