0

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

2
  • Can you show the json string? Commented Mar 22, 2012 at 13:06
  • [{"JSON":"Hey man","Name":"Tim","Age":18}] Commented Mar 22, 2012 at 17:48

2 Answers 2

1

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"));
Sign up to request clarification or add additional context in comments.

9 Comments

[{"JSON":"Hey man","Name":"Tim","Age":18}] this is what I'm trying to reach. In the debugger now I get "Hey man" in result but I still get Nullpointerexception in my onPostExecute.
you can declare constants for the JSON tags like: public static final JSON = "JSON" and get json.getString(JSON); debug the code and check if in json = getData("send.php"); the result json is not null. If you the String result input in onPostExecute is fine then the error may be in the TextView tv.
Check the change i made in my answer
Get an error on publishProgress(json.getString("JSON")); "The method publishProgress(Integer...) in the type AsyncTask<String,Integer,String> is not applicable for the arguments (String)"
change Read extends AsyncTask<String, Integer, String> to Read extends AsyncTask<String, String, String> and update onProgressUpdate.
|
0
        // 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);


                }
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.