1

I have a web service implemented that returns a JSON String as follows:

 {"checkrecord":[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}

In my Android app I am trying to parse the String to a JSONArray but I am unable to do so because I get the following exception in 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

How to solve this issue?

My Android code is as follows:

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;
       }

This is web service code returning 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;

    }
Parth Doshi
  • 4,200
  • 15
  • 79
  • 129

3 Answers3

2

Your result initially is not a JSONArray but rather a JSONObject.

Try this:

JSONObject jsonResult = new JSONObject(new String(reader));

JSONArray jArray = jsonResponse.getJSONArray("checkrecord");
jonsca
  • 10,218
  • 26
  • 54
  • 62
Miguel Teixeira
  • 783
  • 1
  • 10
  • 29
  • what is "reader" ? and with what should I initialize jsonResponse? – Parth Doshi Nov 16 '11 at 17:08
  • while you may be correct about the format of the JSON, the error indicates that the parser is encountering an XML preprocessing instruction, which wouldn't be part of a valid JSON string. – Mike Marshall Nov 16 '11 at 17:08
  • Reader is your BufferedReader. – Miguel Teixeira Nov 16 '11 at 17:19
  • Yes but since his webservice is returning a raw string, the snippet should work... – Miguel Teixeira Nov 16 '11 at 17:21
  • 2
    That is my point, it isn't returning a raw string of JSON. using [WebMethod] with no additional parameters means you will get a SOAP (XML-based) result, with his JSON embedded in the XML. So the fix is to consume the SOAP message on the client and extract the JSON from it or change the web service to return raw JSON. – Mike Marshall Nov 16 '11 at 17:29
  • @mjmarsh:Do you feel this http://stackoverflow.com/questions/6608168/how-to-process-the-soapprimitive-response is what is my problem exactly? – Parth Doshi Nov 16 '11 at 17:34
  • yes, I believe he is also returning JSON as a result inside of a SOAP call. The problem is that all the links posted by the person that answered point to how to parse raw JSON, not on how to call a SOAP method - so I don't think the links will help. My personal preference is to return raw JSON. Here are some ways to do that in WCF: http://stackoverflow.com/questions/2086666/wcf-how-do-i-return-clean-json or http://weblogs.asp.net/jdanforth/archive/2008/08/23/returning-json-from-restful-interface-with-wcf.aspx – Mike Marshall Nov 16 '11 at 17:48
1

Your web service does not return pure JSON, it returns JSON as a string return value from an XML SOAP web service. In fact, it may be an error message in XML since you are not sending a valid SOAP request from the client.

Your URL needs to return raw JSON, with no SOAP XML Envelope around it. Search google for how to write JSON-based web services in ASP.NET, WCF, or another MS technology that may be familiar to you.

Edit

If you want to see the raw result of your URL, try using a tool like Fiddler to monitor the HTTP response.

Also, if you want to make SOAP web service calls from Android, check out ksoap2 for Android

Mike Marshall
  • 7,788
  • 4
  • 39
  • 63
  • ok fine so is there any way I can use the JSON String in my Android app . I am planning to create a TableLayout using the JSON. What should be my approach then? – Parth Doshi Nov 16 '11 at 17:10
  • there are two choices - 1) change your web service to a "REST-like" web service that only returns JSON in the result (https://www.google.com/search?sourceid=chrome&ie=UTF-8&q=rest+json+service+asp.net) or 2) change your client side to make an actual SOAP request like your current web service expects (see my edit link for ksoap2 - a SOAP web services library for Android and mobile platforms) – Mike Marshall Nov 16 '11 at 17:13
  • I tried using SOAP but then again how do I get the response which is of JSON format using ksoap ? – Parth Doshi Nov 16 '11 at 17:13
  • well, that is where Google or Bing will have to come in, but here is a link from a guy that demonstrates a scenario very similar to yours: http://mypetprojects.blogspot.com/2009/05/communication-between-wcf-service-and.html – Mike Marshall Nov 16 '11 at 17:17
  • ok fine will try using SOAP once again. Thanks for the tip !! :-) – Parth Doshi Nov 16 '11 at 17:20
1

Try like this

  JSONObject jsonobject = new JSONObject(result);
  JSONArray array = jsonobject.getJSONArray("checkrecord");
      if(array.length()>0){
          int max = array.length();
        for (int i = 0; i < max; i++) {
            JSONObject tmp = array.getJSONObject(i);
            list.add(tmp.getString("rollno"));
            mandatoryFlagList.add(tmp.getString("percentage"));
        }
     }
Piraba
  • 6,974
  • 17
  • 85
  • 135