java - JSONException:没有值(value)(解析 JSON 图像)

标签 java android json parsing jsonexception

我正在尝试解析 JSON 数据并使该数据在 Android 应用程序的 ListView 中可用。

我收到以下错误:

org.json.JSONException: No value for CarModelImage
07-21 14:03:48.236  25946-25971/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
07-21 14:03:48.236  25946-25971/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.getString(JSONObject.java:510)
07-21 14:03:48.236  25946-25971/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:212)
07-21 14:03:48.236  25946-25971/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:162)
07-21 14:03:48.236  25946-25971/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-21 14:03:48.236  25946-25971/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-21 14:03:48.236  25946-25971/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-21 14:03:48.236  25946-25971/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-21 14:03:48.236  25946-25971/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-21 14:03:48.236  25946-25971/com.example.justin.myapplication W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
07-21 14:03:48.252  25946-25946/com.example.justin.myapplication V/List parsed﹕ []

我的代码:

public class JSONBuilderActivity extends ListActivity {

    private ProgressDialog pDialog;

    //URL to get JSON
    private static String url = "";

    //JSON Node names
    private static final String TAG_CARS = "cars";      //root
    private static final String TAG_CARID = "CarID";
    private static final String TAG_MODELIMG = "CarModelImage";

    JSONArray carid = null;  //Initializes JSON array

    static String response = null;

    //Hashmap for ListView
    ArrayList<HashMap<String, String>>caridList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ListView lv = getListView();

        //Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //Gets values from selected ListItem
                String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString();
                String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
                String model_img = ((ImageView) view.findViewById(R.id.model_img)).toString();

                Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class);
                //getApplicationContext()
                //sending data to new activity
                in.putExtra("TAG_CARS", cars);
                in.putExtra("TAG_CARID", car_id);
                in.putExtra("TAG_MODELIMG", model_img);
                startActivity(in);
            }
        });

        //Calls async task to get json
        new GetCars().execute();
    }

    public class ServiceHandler {

        public final static int GET = 1;
        public final static int POST = 2;

        public ServiceHandler() {

        }

        /**
         * Makes service call
         * @url - url to make request
         * @method - http request method
         * */
        public String makeServiceCall(String url, int method) {
            return this.makeServiceCall(url, method, null);
        }

        /**
         * Makes service call
         * @url - url to make request
         * @method - http request method
         * @params - http request params
         * */
        public String makeServiceCall(String url, int method,ArrayList<NameValuePair> params) {
                    try {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpEntity httpEntity = null;
                    HttpResponse httpResponse = null;

                    //Checks http request method type
                    if (method == POST) {
                        HttpPost httpPost = new HttpPost(url);

                        //Adds post params
                    if (params != null) {
                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                    }

                        httpResponse = httpClient.execute(httpPost);

                } else if (method == GET) {

                    //Appends params to url
                    if (params != null) {
                        String paramString = URLEncodedUtils.format(params, "utf-8");
                        url += "?" + paramString;
                    }
                        HttpGet httpGet = new HttpGet(url);

                        httpResponse = httpClient.execute(httpGet);
                }

                httpEntity = httpResponse.getEntity();
                response = EntityUtils.toString(httpEntity);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return response;

        }
    }

    /*
     * Async task class to get json by making HTTP call
     */
    private class GetCars extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            caridList = new ArrayList<HashMap<String, String>>();

            //Shows progress dialog
            pDialog = new ProgressDialog(JSONBuilderActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            //Creates service handler class instance
            ServiceHandler sh = new ServiceHandler();

            //Makes a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            //Prints the json response in the log
            Log.d("GetCars response: ", "> " + jsonStr);

            //Prints array in app


                    if (jsonStr != null) {
                        try {

                            Log.d("try", "in the try");

                            JSONObject jsonObj = new JSONObject(jsonStr);
                            Log.d("jsonObject", "new json Object");

                            //Gets JSON Array node
                            carid = jsonObj.getJSONArray(TAG_CARS);
                            Log.d("json array", "user point array");

                            int len = carid.length();
                            Log.d("len", "get array length");

                            for (int i = 0; i < carid.length(); i++) {
                                JSONObject c = carid.getJSONObject(i);
                                String car_id = c.getString(TAG_CARID);
                                Log.d("car_id", car_id);

                                String jsonString = jsonObj.getString(TAG_MODELIMG);
                                getBitmapFromString(jsonString);
                                String model_img = c.getString(TAG_MODELIMG);
                                Log.d("model_img", model_img);

                                //Hashmap for single match
                                HashMap<String, String> matchGetCars = new HashMap<String, String>();

                                //Adds each child node to HashMap key => value
                                matchGetCars.put(TAG_CARID, car_id);
                                matchGetCars.put(TAG_MODELIMG, model_img);
                                caridList.add(matchGetCars);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.e("ServiceHandler", "Couldn't get any data from the url");
                    }

                   return null;
                }


        private Bitmap getBitmapFromString(String jsonString) {
            byte[] decodedString = Base64.decode("CarModelImage", Base64.DEFAULT);
            Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
            return decodedByte;
        }

@Override
                protected void onPostExecute(Void result) {
                    super.onPostExecute(result);
                    //Dismisses the progress dialog
                    if (pDialog.isShowing())
                        pDialog.dismiss();

                    /**
                     * Updates parsed JSON data into ListView
                     * */
                   ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
                           new String[]{TAG_CARID, TAG_MODELIMG}, new int[]{R.id.car_id, R.id.model_img});
                   setListAdapter(adapter);
                    Log.v("List parsed", caridList.toString());
                }
    }
}

我知道错误发生在以下位置,但我不明白哪里出了问题:

 if (jsonStr != null) {
                    try {

                        Log.d("try", "in the try");

                        JSONObject jsonObj = new JSONObject(jsonStr);
                        Log.d("jsonObject", "new json Object");

                        //Gets JSON Array node
                        carid = jsonObj.getJSONArray(TAG_CARS);
                        Log.d("json array", "user point array");

                        int len = carid.length();
                        Log.d("len", "get array length");

                        for (int i = 0; i < carid.length(); i++) {
                            JSONObject c = carid.getJSONObject(i);
                            String car_id = c.getString(TAG_CARID);
                            Log.d("car_id", car_id);

                            String jsonString = jsonObj.getString(TAG_MODELIMG);
                            getBitmapFromString(jsonString);
                            String model_img = c.getString(TAG_MODELIMG);
                            Log.d("model_img", model_img);

                            //Hashmap for single match
                            HashMap<String, String> matchGetCars = new HashMap<String, String>();

                            //Adds each child node to HashMap key => value
                            matchGetCars.put(TAG_CARID, car_id);
                            matchGetCars.put(TAG_MODELIMG, model_img);
                            caridList.add(matchGetCars);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }

               return null;
            }

JSON 数组的简要 View :

{"cars":[{"id":1,"CarID":"20946","CarModelImage":"JDMQ.jpg".....so on...

我很感激任何关于为什么会发生这种情况的见解。谢谢。

(P.S.:我意识到有很多类似的帖子,我尝试应用他们的解决方案,但没有成功。)

最佳答案

当您打算在 c 上调用 getString 时,您正在对 jsonObj 调用它。

关于java - JSONException:没有值(value)(解析 JSON 图像),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31546662/

相关文章:

ios - 出现-[__ NSCFDictionary objectAtIndex:]错误:无法识别的选择器已发送到实例

java - 我将如何检查用户是否单击了 fillRect 生成的正方形并在单击时执行操作?

java - 通过 JavaFX 过滤 JDK 错误系统

android - 视口(viewport)高度在键盘打开android上改变

json - 从 T-SQL 查询将键值对输出为 JSON

mysql - 如何使用 mvc spring 将 JSON 数组插入 MySQL

java - 在下面的代码中将 Big Decimal 初始化为 -99 的含义

java - 如何在 JSP 上转义撇号或引号(由 JavaScript 使用)

android - 计算距离相机远近的移动物体的速度

android - Fabric 和 Crashlytics 不适用于 Bazel 构建