【问题标题】:jsonexception of type org.json.JSONObject cannot be converted to JSONArrayorg.json.JSONObject 类型的 jsonexception 无法转换为 JSONArray
【发布时间】:2012-03-22 13:00:36
【问题描述】:

我正在尝试从网页读取 JSON 字符串,但得到错误 jsonexception of type org.json.JSONObject cannot be convert to JSONArray。

最终静态字符串 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 我在 logcat 中得到了这个,当我调试时它说: org.json.JSONObject 类型的 jsonexception 无法转换为 JSONArray

【问题讨论】:

  • 可以显示json字符串吗?
  • [{"JSON":"Hey man","Name":"Tim","Age":18}]

标签: android json parsing


【解决方案1】:

尝试做:

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

如果 JSON 字符串在数组中只有一个元素,请注意。如果您想从服务器发布 JSON 字符串响应以进行分析。

尝试使用 onProgressUpdate:

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

最后 int doInBackground 调用:

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

【讨论】:

  • [{"JSON":"Hey man","Name":"Tim","Age":18}] 这就是我想要达到的目标。现在在调试器中,我得到“嘿,伙计”的结果,但我的 onPostExecute 中仍然得到 Nullpointerexception。
  • 您可以为 JSON 标签声明常量,例如: public static final JSON = "JSON" 并获取 json.getString(JSON);调试代码并检查 json = getData("send.php");结果 json 不为空。如果您在 onPostExecute 中输入的字符串结果很好,那么错误可能在 TextView tv 中。
  • 检查我在回答中所做的更改
  • 在 publishProgress(json.getString("JSON")) 上获取错误; “AsyncTask 类型中的方法 publishProgress(Integer...) 不适用于参数 (String)”
  • 将 Read extends AsyncTask 更改为 Read extends AsyncTask 并更新 onProgressUpdate。
【解决方案2】:
        // 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);


                }
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多