как исправить исключение несоответствия типа json при разборе URL-адреса json в Android?

#android #json

#Android #json

Вопрос:

Я пытаюсь получить Json данные с помощью URL . Мой массив Json размещен ниже. Я получаю исключение несоответствия типа json. Может ли кто-нибудь пошагово указать мне, где я ошибаюсь? Мои журналы ошибок размещены ниже.

Во-вторых, пожалуйста, скажите мне, является ли синтаксический анализ json с использованием URL-адреса таким же, как синтаксический анализ json с использованием php из базы данных сервера.

Url : http://166.62.17.208/json_preferencess.aspx

  "items": [
        {
            "id": "11",
            "Item_Id": "123",   
            "Item_Name": "Chicken Cream Soup",
            "Price": "8",
            "Currency": "AED",
            "Category": "Soup",
            "Description": "Creamy Chicken Soup with garnish amp; side helpings",
            "Unit": "2",
            "food_type": "Non",
            "Image_Large": "/images_large/chickensoup.jpg",
            "Image_Thumb": "/images_large/chickensoup.jpg",
            "Timestamp": "6/23/2014 9:49:43 PM",
            "Promotion": "",
            "Item_Name_arabic": "حساء الطماطم",
            "Item_Name_russian": "",
            "Currency_arabic": "درهم",
            "Currency_russian": "",
            "Description_arabic": "حساء الطماطم",
            "Description_russian": "",
            "Note": "",
            "Nutritional_info": "",
            "extrafield_1": "",
            "extrafield_2": "",
            "preferncess": [
                "No Salt",
                "Extra Sugar"
            ],
            "preferncess_ids": [
                "1",
                "2"
            ],
            "price": [
                "4",
                "5"
            ],
            "preferncess_arabic": [
                "لا الملح",
                "سكر اضافية"
            ]
        }
        ],
    "category_Timestamp": "6/24/2014 1:05:28 PM",
    "questions": [
        {
            "q_id": "1",
            "q_question": "How would you rate our Menu ?",
            "q_option1": "Excellent",
            "q_option2": "Very Good",
            "q_option3": "Good",
            "q_option4": "Bad",
            "q_option5": "Terrible",
            "Timestamp": "9/12/2013 3:31:55 PM",
            "q_status": "1"
        },
         ],
 

MainActivity.class

 String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> "   jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                //items = jsonObj.getJSONArray(TAG_CONTACTS);
                Log.i("json node","" jsonObj);

                // looping through All Contacts
                for (int i = 0; i < items.length(); i  ) {
                    JSONObject c = items.getJSONObject(i);

                    String id = c.getString("id");
                           }
                            }
 

Журналы ошибок

     06-27 06:55:50.154: W/System.err(2192): org.json.JSONException: Value [{"questions":[{"q_id":"1","q_question":"How would you rate our Menu ?","q_status":"1","q_option5":"Terrible","q_option3":"Good","q_option4":"Bad","q_option2":"Very Good","q_option1":"Excellent","Timestamp":"9/12/2013 3:31:55 PM"},{"q_id":"2","q_question":"How would you rate our presentation, taste and quality of food ?","q_status":"1","q_option5":"Terrible","q_option3":"Good","q_option4":"Bad","q_option2":"Very Good","q_option1":"Excellent","Timestamp":"9/12/2013 3:31:55 PM"},{"q_id":"3","q_question":"How would you rate the friendliness our staff members ?","q_status":"1","q_option5":"Terrible","q_option3":"Good","q_option4":"Bad","q_option2":"Very Good","q_option1":"Excellent","Timestamp":"9/12/2013 3:31:55 PM"},{"q_id":"4","q_question":"How would you rate our staff's performance and service?","q_status":"1","q_option5":"Terrible","q_option3":"Good","q_option4":"Bad","q_option2":"Very Good","q_option1":"Excellent","Timestamp":"9/12/2013 3:31:55 PM"},{"q_id":"5","q_question":"How would you rate the value for money ?","q_status":"1","q_option5":"Terrible","q_option3":"Good","q_option4":"Bad","q_option2":"Very Good","q_option1":"Excellent","Timestamp":"9/12/2013 3:31:55 PM"}],"categories":[{"categoryArabicName":"سلطة خضراء","catid":"0","categoryShortName":"Salads","categoryName":"Salads"},{"categoryArabicName":"المزة","catid":"1","categoryShortName":"Mezzah","categoryName":"Mezzah"},{"categoryArabicName":"الطبق الرئيسي","catid":"2","categoryShortName":"Main-Course","categoryName":"Main Course"},{"categoryArabicName":"معكرونة","catid":"3","categoryShortName":"Pasta","categoryName":"Pasta"},{"categoryArabicName":"مثوبة","catid":"4","categoryShortName":"Deserts","categoryName":"Deserts"},{"categoryArabicName":"حساء","catid":"5","categoryShortName":"Soup","categoryName":"Soup"}],"question_Timestamp":"9/12/2013 3:31:55 PM","items":[{"Image_Large":"/images_large/chickensoup.jpg","Promotion":"","food_type":"Non","Item_Name":"Chicken Cream Soup","Unit":"2","id":"11","Nutritional_info":"","Description_arabic":"حساء الطماطم","Image_Thumb":"/images_large/chickensoup.jpg","preferncess":["No Salt","Extra Sugar"],"extrafield_1":"","extrafield_2":"","Currency":"AED","Description_russian":"","Description":"Creamy Chicken Soup with garnish amp; side helpings","preferncess_ids":["1","2"],"Item_Name_russian":"","Currency_russian":"","Note":"","Item_Id":"123","preferncess_arabic":["لا الملح","سكر اضافية"],"Timestamp":"6/23/2014 9:49:43 PM","Category":"Soup","price":["4","5"],"Currency_arabic":"درهم","Price":"8","Item_Name_arabic":"حساء الطماطم"},{"Image_Large":"/images_large/pasta.jpg","Promotion":"","food_type":"Non","Item_Name":"Pasta Napolitan","Unit":"20","id":"12","Nutritional_info":"","Description_arabic":"حساء الطماطم","Image_Thumb":"/images_large/pasta.jpg","preferncess":["No Salt"],"extrafield_1":"","extrafield_2":"","Currency":"AED","Description_russian":"","Description":"Pasta in Napolitan Sauce","preferncess_ids":["3"],"Item_Name_russian":"","Currency_russian":"","Note":"","Item_Id":"501","preferncess_arabic":["لا الملح"],"Timestamp":"6/23/2014 9:47:45 PM","Category":"Pasta","price":["5"],"Currency_arabic":"درهم","Price":"18","Item_Name_arabic":"حساء الطماطم"},{"Image_Large":"/images_large/caeser-salad.jpg","Promotion":"","food_type":"Non","Item_Name":"Caeser Salad","Unit":"20","id":"13","Nutritional_info":"","Description_arabic":"حساء الطماطم حساء الطماطم حساء الطماطم حساء الطماطمحساء الطماطم","Image_Thumb":"/images_large/caeser-salad.jpg","preferncess":["No Salt","Extra Pepper"],"extrafield_1":"","extrafield_2":"","Currency":"AED","Description_russian":"","Description":"A Caesar salad is a salad of romaine lettuce and croutons dressed with Parmesan cheese.","preferncess_ids":["4","8"],"Item_Name_russian":"","Currency_russian":"","Note":"","Item_Id":"1001","preferncess_arab


   W/System.err(2122):  at org.json.JSON.typeMismatch(JSON.java:111)
   W/System.err(2122):  at org.json.JSONObject.<init>(JSONObject.java:159)
   W/System.err(2122):  at org.json.JSONObject.<init>(JSONObject.java:172)
   W/System.err(2122):  at info.androidhive.jsonparsing.MainActivity$GetContacts.doInBackground(MainActivity.java:118)
   W/System.err(2122):  at info.androidhive.jsonparsing.MainActivity$GetContacts.doInBackground(MainActivity.java:1)
   W/System.err(2122):  at android.os.AsyncTask$2.call(AsyncTask.java:288)
   W/System.err(2122):  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
   W/System.err(2122):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
  W/System.err(2122):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
  W/System.err(2122):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
  W/System.err(2122):   at java.lang.Thread.run(Thread.java:841)
 

Ответ №1:

Прежде всего, ваши данные поступают с сервера в виде массива, и вы пытаетесь преобразовать данные в объект json.

Теперь попробуйте следующий метод:-

                 JSONArray obj = new JSONArray(jsonStr);
                JSONObject obj = jsonObj.getJSONObject(0);

                items = jsonObj.getJSONArray("items");
                for (int i = 0; i < items.length(); i  ) 
                {
                    JSONObject c = items.getJSONObject(i);

                    String id = c.getString("id");
                }
 

Я думаю, вы не получаете массив элементов, поэтому вы получаете ошибку.

Комментарии:

1. @user3256145 dnt mind покажет нам всю строку json?

2. вы хотите, чтобы я опубликовал всю строку json? @Golu

3. Я опубликовал URL-адрес и строку. пожалуйста, проверьте

Ответ №2:

Попробуйте проверить тип следующим образом перед приведением

 if (c.get(key) instanceof String)
                     {
                        JSONObject Lawset = c.getString(key);                        
                     } else if (c.get(key) instanceof JSONObject)
                     {
                        JSONObject Lawset = c.getJSONObject(key);                        

                        //try to retrieve data from json object
                     }
                     else if (c.get(key) instanceof JSONArray)
                    {
                        JSONArray Lawset = c.getJSONArray(key);
                                    //iterate to get data
                    }
 

Ответ №3:

Попробуйте этот способ, надеюсь, это поможет вам решить вашу проблему.

         String jsonStr = "{"items":[{"id":"11","Item_Id":"123","Item_Name":"Chicken Cream Soup","Price":"8","Currency":"AED","Category":"Soup","Description":"Creamy Chicken Soup with garnish amp; side helpings","Unit":"2","food_type":"Non","Image_Large":"/images_large/chickensoup.jpg","Image_Thumb":"/images_large/chickensoup.jpg","Timestamp":"6/23/2014 9:49:43 PM","Promotion":"","Item_Name_arabic":"حساء الطماطم","Item_Name_russian":"","Currency_arabic":"درهم","Currency_russian":"","Description_arabic":"حساء الطماطم","Description_russian":"","Note":"","Nutritional_info":"","extrafield_1":"","extrafield_2":"","preferncess":["No Salt","Extra Sugar"],"preferncess_ids":["1","2"],"price":["4","5"],"preferncess_arabic":["لا الملح","سكر اضافية"]}],"category_Timestamp":"6/24/2014 1:05:28 PM","questions":[{"q_id":"1","q_question":"How would you rate our Menu ?","q_option1":"Excellent","q_option2":"Very Good","q_option3":"Good","q_option4":"Bad","q_option5":"Terrible","Timestamp":"9/12/2013 3:31:55 PM","q_status":"1"}]}";
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                JSONArray items = jsonObj.getJSONArray("items");
                for (int i = 0; i < items.length(); i  ) {
                    System.out.println(i   1   " Id :"   items.getJSONObject(i).getString("id"));
                    System.out.println(i   1   " Item Id :"   items.getJSONObject(i).getString("Item_Id"));
                    System.out.println(i   1   " Item Name :"   items.getJSONObject(i).getString("Item_Name"));
                    System.out.println(i   1   " Currency :"   items.getJSONObject(i).getString("Currency"));
                    System.out.println(i   1   " Category :"   items.getJSONObject(i).getString("Category"));
                    System.out.println(i   1   " Description :"   items.getJSONObject(i).getString("Description"));
                    System.out.println(i   1   " Unit :"   items.getJSONObject(i).getString("Unit"));
                    System.out.println(i   1   " Food Type :"   items.getJSONObject(i).getString("food_type"));
                    System.out.println(i   1   " Image Large :"   items.getJSONObject(i).getString("Image_Large"));
                    System.out.println(i   1   " Image Thumb :"   items.getJSONObject(i).getString("Image_Thumb"));
                    System.out.println(i   1   " Timestamp :"   items.getJSONObject(i).getString("Timestamp"));
                    System.out.println(i   1   " Promotion :"   items.getJSONObject(i).getString("Promotion"));
                    System.out.println(i   1   " Item Name Arabic :"   items.getJSONObject(i).getString("Item_Name_arabic"));
                    System.out.println(i   1   " Item Name Russian :"   items.getJSONObject(i).getString("Item_Name_russian"));
                    System.out.println(i   1   " Currency Arabic :"   items.getJSONObject(i).getString("Currency_arabic"));
                    System.out.println(i   1   " Currency Russian :"   items.getJSONObject(i).getString("Currency_russian"));
                    System.out.println(i   1   " Description Arabic :"   items.getJSONObject(i).getString("Description_arabic"));
                    System.out.println(i   1   " Description Russian :"   items.getJSONObject(i).getString("Description_russian"));
                    System.out.println(i   1   " Note :"   items.getJSONObject(i).getString("Note"));
                    System.out.println(i   1   " Nutritional Info :"   items.getJSONObject(i).getString("Nutritional_info"));
                    System.out.println(i   1   " Extrafield_1 :"   items.getJSONObject(i).getString("extrafield_1"));
                    System.out.println(i   1   " Extrafield_2 :"   items.getJSONObject(i).getString("extrafield_2"));

                    JSONArray preferncess = items.getJSONObject(i).getJSONArray("preferncess");

                    for (int j = 0; j < preferncess.length(); j  ) {
                        System.out.println("Preferncess "   j   1   ":"   preferncess.getString(j));
                    }

                    JSONArray preferncess_ids = items.getJSONObject(i).getJSONArray("preferncess_ids");

                    for (int j = 0; j < preferncess_ids.length(); j  ) {
                        System.out.println("Preferncess IDs "   j   1   ":"   preferncess_ids.getString(j));
                    }
                    JSONArray price = items.getJSONObject(i).getJSONArray("price");

                    for (int j = 0; j < price.length(); j  ) {
                        System.out.println("Price"   j   1   ":"   price.getString(j));
                    }
                    JSONArray preferncess_arabic = items.getJSONObject(i).getJSONArray("preferncess_arabic");

                    for (int j = 0; j < preferncess_arabic.length(); j  ) {
                        System.out.println("Preferncess Arabic"   j   1   ":"   preferncess_arabic.getString(j));
                    }


                    System.out.println("Category TimeStamp :"   jsonObj.getString("category_Timestamp"));

                    JSONArray questions = jsonObj.getJSONArray("questions");
                    for (int k = 0; k < questions.length(); k  ) {
                        System.out.println(i   1   " Question Id :"   questions.getJSONObject(k).getString("q_id"));
                        System.out.println(i   1   " Question :"   questions.getJSONObject(k).getString("q_question"));
                        System.out.println(i   1   " Question Option 1 :"   questions.getJSONObject(k).getString("q_option1"));
                        System.out.println(i   1   " Question Option 2 :"   questions.getJSONObject(k).getString("q_option2"));
                        System.out.println(i   1   " Question Option 3 :"   questions.getJSONObject(k).getString("q_option3"));
                        System.out.println(i   1   " Question Option 4 :"   questions.getJSONObject(k).getString("q_option4"));
                        System.out.println(i   1   " Question Option 5 :"   questions.getJSONObject(k).getString("q_option5"));
                        System.out.println(i   1   " Question Timestamp :"   questions.getJSONObject(k).getString("Timestamp"));
                        System.out.println(i   1   " Question Status :"   questions.getJSONObject(k).getString("q_status"));
                    }
                }
            }catch (Throwable e){
                e.printStackTrace();
            }
        }