simtaxman
simtaxman

Reputation: 623

jsonexception of type org.json.JSONObject cannot be converted to JSONArray

I'm trying to read a JSON string from a webpage but get the error jsonexception of type org.json.JSONObject cannot be converted to JSONArray.

final static String URL = "http://www2.park.se/~ts5124/";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tv = (TextView)findViewById(R.id.text1);
    client = new DefaultHttpClient();
    new Read().execute("JSON");


    if (logged=="yes") {
        setContentView(R.layout.main);
    } else {
        setContentView(R.layout.login);
        b1 = (Button)findViewById(R.id.btn);
        name = (EditText)findViewById(R.id.name);
        pass = (EditText)findViewById(R.id.password);



        b1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub


                 try {
                     JSONObject json = new JSONObject();
                     HttpClient httpclient = new DefaultHttpClient();
                     HttpPost httppost = new HttpPost("http://www2.park.se/~ts5124/login.php");



                     json.put("userName", name.getText().toString());
                     json.put("password", pass.getText().toString());

                     StringEntity se;
                     se = new StringEntity(json.toString(), "UTF-8");

                     // Add your data
                     httppost.setEntity(se);
                     httppost.setHeader("Accept", "application/json");
                     httppost.setHeader("Content-type", "application/json");


                     Log.i(TAG, json.toString());

                     // Execute HTTP Post Request
                     httpclient.execute(httppost);

                 } catch (JSONException je) {


                 } catch (IOException e) {
                     // TODO Auto-generated catch block
                 }
            }
        });
    }


}

public JSONObject getData(String page) throws ClientProtocolException, IOException, JSONException {
    StringBuilder url = new StringBuilder(URL);
    url.append(page);

    HttpGet get = new HttpGet(url.toString());
     HttpResponse r = client.execute(get);
     int status = r.getStatusLine().getStatusCode();
     if (status == 200) {
        HttpEntity e = r.getEntity();
        String data = EntityUtils.toString(e);
        JSONArray timeline = new JSONArray(data);
        JSONObject last = timeline.getJSONObject(0);
        return last;
     } else {
         Log.i("JSON","Ain't workin'");
         return null;
     }
  }

  public class Read extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
       try {
          json = getData("send.php");
          return json.getString(params[0]);
       } catch (ClientProtocolException e) {
          return e.toString();
       } catch (IOException e) {
          return e.toString();
       } catch (JSONException e) {
          return e.toString();
       }
    }

    @Override
    protected void onPostExecute(String result) {
       tv.setText(result);
    }
  }

http://pastebin.com/dUnmsEd6 I get this in the logcat and when i debug it says: jsonexception of type org.json.JSONObject cannot be converted to JSONArray

Upvotes: 0

Views: 6525

Answers (2)

Douglas Tybel
Douglas Tybel

Reputation: 59

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(uri.toString());

        try {
            //Obter objeto JSON
            clientesJSONArray = json.optJSONArray(Clientes.TABELA);

            //Se for 1 objeto não virá em JSONArray - Os objetos em JSON são separados
            //por colchetes [] - No caso de um objeto, não será array e sim um simples
            //objeto em JSON
            if(clientesJSONArray==null){
                // means item is JSONObject instead of JSONArray
                //json = obj.optJSONObject("offerRideResult");
                JSONObject obj = json.getJSONObject(Clientes.TABELA);

                Clientes oCliente = new Clientes();
                oCliente.setCliente(obj.getString(Clientes.CLIENTE));
                oCliente.setCod_cliente(obj.getInt(Clientes.COD_CLIENTE));
                oCliente.setE_mail(obj.getString(Clientes.E_MAIL));
                oCliente.setUsuario(obj.getString(Clientes.USUARIO));
                oCliente.setUsuario(obj.getString(Clientes.SENHA));


                clientesList.add(oCliente);

            }else{
                // Mais de um objeto JSON separado por colchetes [] - JSONArray ao invés JSONObject
                for (int i = 0; i < clientesJSONArray.length(); i++) {

                    JSONObject obj = clientesJSONArray.getJSONObject(i);
                    Clientes oCliente = new Clientes();
                    oCliente.setCliente(obj.getString(Clientes.CLIENTE));
                    oCliente.setCod_cliente(obj.getInt(Clientes.COD_CLIENTE));
                    oCliente.setE_mail(obj.getString(Clientes.E_MAIL));
                    oCliente.setUsuario(obj.getString(Clientes.USUARIO));
                    oCliente.setUsuario(obj.getString(Clientes.SENHA));


                    clientesList.add(oCliente);


                }
            }

Upvotes: 0

V&#237;tor Marques
V&#237;tor Marques

Reputation: 349

try doing:

JSONArray timeline = new JSONArray(data);
String s = timeline.get(0).toString();
JSONObject last = new JSONObject(s);

pay attention also if the JSON String has only one element in the array. If you want post the JSON String response from the server to analyse.

try using the onProgressUpdate:

protected void onProgressUpdate(String... result){
tv.setText(result[0]);
}

and int the doInBackground call in the end:

publishProgress(json.getString("JSON"));

Upvotes: 1

Related Questions