-1

Error:

W/System.err﹕ org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject

W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)

W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:158)

W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:171)

Code :

Inside a try block

            post.setEntity(new UrlEncodedFormEntity(data_to_send));
            HttpResponse httpResponse = client.execute(post);

            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);


            JSONObject jsonObject = new JSONObject(result);

            if(jsonObject.length() == 0)
            {
                retunedContact = null;

            }
            else
            {
                String name,email;
                name = null;
                email=null;

                if(jsonObject.has("name"))
                    name = jsonObject.getString("name");
                if(jsonObject.has("email"))
                    email =jsonObject.getString("email");

                retunedContact = new Contact(name , email , contact.username , contact.password);

            }


        catch(Exception e)
        {
            e.printStackTrace();
        }
Miguel Benitez
  • 2,322
  • 10
  • 22
Vinay
  • 1
  • 2

2 Answers2

0

Your result seems to be a JSONArray like [..] instead of a JSONObject like {..}

Instead of JsonObject use JsonArray, i.e. for example like this:

try {
    JSONArray myJsonArray = new JSONArray(result);
} catch (JSONException e) {
    // log Error
}
Diyarbakir
  • 1,999
  • 18
  • 36
  • then i get an error for this code: cannot reslove method has in if(jsonObject.has("name")) name = jsonObject.getString("name"); if(jsonObject.has("email")) email =jsonObject.getString("email"); – Vinay Apr 11 '16 at 13:49
  • `JSONArray` objects have a function `getJSONObject(int index)` and you can loop through all of the `JSONObject` by writing a simple for-loop. – Diyarbakir Apr 11 '16 at 13:53
  • JSONArray jsonObject = new JSONArray(result); for(int i=0;i – Vinay Apr 11 '16 at 14:04
  • See http://stackoverflow.com/questions/7634518/getting-jsonobject-from-jsonarray/7634559#7634559 – Diyarbakir Apr 11 '16 at 14:08
0

I think what format you get from the api is

[
  {
     "somekey":"somevalue",
     "somekey2":"somevalue2"
  },

  {
     "somekey":"somevalue",
     "somekey2":"somevalue2"
  }
]

then you should know that this format is a JSONArray not a JSONObject. So, Better to try either this Code

JSONParser parser = new JSONParser() 
JSONObject jsonObject = (JSONArray)parser.parse(result);

or

try {
    JSONArray obj_JSONArray= new JSONArray(result);
} catch (JSONException e) {
    e.printStackTrace();
}
Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52