【问题标题】:What is The meaning of org.json.JSONException in Android?Android中的org.json.JSONException是什么意思?
【发布时间】:2014-04-02 10:11:01
【问题描述】:

我正在开发一个 JSON 对象的应用程序,它将数据返回到 ListView。

在那个需要传递的参数是用户的uid。

我的异步代码是:

class  AsyncCallWebServicereceiveHistory extends AsyncTask<String, String, String>
{
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        progressDialog = new ProgressDialog(ReceiveHistory.this);
        progressDialog.setTitle("Loading");
        progressDialog.setMessage("Please wait");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... aurl)
    {
        Log.v("receiveHistory","Do in BG-1");
        uid=global.get_user_id();
        try
        {
            HttpPost postMethod = new HttpPost("http://demo1.idevtechnolabs.com/RChatAPI/receive_history.php");

            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("uemail", uid));
            BufferedReader bufferedReader = null;

            HttpClient client = new DefaultHttpClient();
            HttpResponse response = null;

            response = client.execute(postMethod);
            final int statusCode = response.getStatusLine().getStatusCode();

            Log.v("Album ::","Response:::--->"+response.toString());
            Log.v("Album ::","Status Code:::--->"+statusCode);

            bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer stringBuffer = new StringBuffer("");
            String line = "";
            String LineSeparator = System.getProperty("line.separator");
            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuffer.append(line + LineSeparator);
            }
            bufferedReader.close();

            //-------------CONVERT DATA TO JSON---------------------------------

            try
            {
                String myjsonstring = stringBuffer.toString();

                JSONArray jsonArray = new JSONArray(myjsonstring);

                JSONObject jsonObj = null;

                jsonObj = jsonArray.getJSONObject(0);
                code = jsonObj.getString("code");
                receiveMsgData.clear();

                Log.v("Home ::","Code:::--->"+code);

                code="0";
                if(code.equals("0"))
                {
                    for(int i=0; i<jsonArray.length();i++)
                    {

                            jsonObj = jsonArray.getJSONObject(i);
                            uname=jsonObj.getString("name");
                            uage = jsonObj.getString("age");
                            usex = jsonObj.getString("sex");
                            body = jsonObj.getString("country");
                            text= jsonObj.getString("text");

                            HashMap<String, String> tmp_album = new HashMap<String, String>();
                            tmp_album.put("receive_data", "Text");
                            Log.v("receive History","receive Data");
                            receiveMsgData.add(tmp_album);

                    }
                }
                catch (Exception e)
                {
                    Log.v("Home ::","Call JSON Exception in get Album in List--->"+e.toString());
                    e.printStackTrace();
                }
            }
            catch (Exception e)
            {
                Log.v("Exception: Get get Album in List","Name-"+e.toString());
                e.printStackTrace();
            }

            return code;
        }

        @Override
        protected void onPostExecute(String code)
        {
            if(code.equals("0"))
            {
                Receive_History_Custom_Adapter adapter = new Receive_History_Custom_Adapter(getApplicationContext(), receiveMsgData);
                lv.setAdapter(adapter);

            }
            else
            {
                Toast.makeText(getApplicationContext(), "Data not found", Toast.LENGTH_SHORT).show();
            }

            try
            {
                progressDialog.dismiss();
                progressDialog = null;
            }
            catch (Exception e)
            {
                // nothing
            }
        }
    }
}

我得到以下异常:

Call JSON Exception in get Album in List--->org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject

我的 Json 响应是:

[
    {
        "code":"0", "user_id":"21", "msg_id":"115", "name":"Sagar", "age":"18", "sex":"Male", "country":
        " India", "text":"hi", "photo":"demo.idevtechnolabs.com", "cnt":"1"
    },
    {
        "code":"0", "user_id":"18", "msg_id":"114", "name":"Ramani", "age":"20", "sex":"Male", "country":
        "Pakistan", "text":"hi", "photo":"demo.idevtechnolabs.com", "cnt":"1"
    }
]

谁能告诉我这是什么原因,请问我该如何解决。

提前致谢!

【问题讨论】:

  • 如果可以,请发布您的 json 响应
  • Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject 您的 json 是 JSONArray 但您正在尝试将其转换为 JSONObject
  • 好的,那么我该如何解决这个@Raghunandan
  • 查看我编辑的问题@user2450263
  • @NiravDabhi 确定这是完整的 json,并在不需要 for(int i=0; i&lt;jsonArray.length();i++){for(int i=0; i&lt;4;i++) 的情况下发布完整的堆栈跟踪和 2 个 for 循环

标签: android json arrays jsonobject jsonexception


【解决方案1】:

如果该项目的代码等于0,我认为您正在尝试将JSONArray 中的每个项目添加到消息列表中。如果是这样,你的代码是错误的,重写它比解释更容易:

try {
    String myjsonstring = stringBuffer.toString();
    JSONArray jsonArray = new JSONArray(myjsonstring);
    receiveMsgData.clear();
    for (int i = 0; i < jsonArray.length(); i++) {
        if (jsonArray.getJSONObject(i).getInt("code") == 0) {
            JSONObject data = jsonArray.getJSONObject(i);
            HashMap<String, String> tmp_album = new HashMap<String, String>();
            tmp_album.put("name", data.getString("name"));
            tmp_album.put("age", data.getString("age"));
            tmp_album.put("sex", data.getString("sex"));
            tmp_album.put("country", data.getString("country"));
            tmp_album.put("text", data.getString("text"));
            receiveMsgData.add(tmp_album);
        }
    }

} catch (Exception e) {
    Log.v("Home ::", "Call JSON Exception in get Album in List--->" + e.toString());
    e.printStackTrace();
}

这里我们遍历JSONArray 并检查code 是否等于0。如果相等,我们将必要的字段放入临时的HashMap,然后将其附加到消息列表中。

【讨论】:

  • 0 不是 int 它是 String 你能根据这个帮我吗?如果代码返回 0,那么数据应该是 Pass
  • @NiravDabhi 试试这个代码。字符串“0”可以解析为int,所以我们可以使用getInt
  • 它返回 Null 作为代码“0”,所以异常是相同的。
  • @NiravDabhi 在这种情况下显示myjsonstring的确切值
  • 你能解释一下这个错误的原因是什么,因为我尝试了很多,但我一直都遇到同样的错误。
猜你喜欢
  • 1970-01-01
  • 2011-08-12
  • 2017-06-11
  • 2018-03-05
  • 2023-03-27
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多