2016-11-21 2 views
-1

У меня есть формат json, как показано ниже. Как его получить в listview в android, Пока я пытаюсь сделать, после ошибки увеличивается. I, m имеет несколько квадратных квадратных скобок стартового массива.Как получить массив json внутри массива в android listview

    org.json.JSONException: Value [{"id":"30","title":"Android Design Engineer","postedDate":"2016-11-19","jobtype":"Contract","location":"Alabama","description":"Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world","experience":"2 to 6 yrs","salary":" Upto $50"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject 

и следующий мой код Java, здесь я вызываю jsosarray и разбиваю его на объекты.

 try { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail"); 
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse httpResponse = httpClient.execute(httpPost); 
      int code = httpResponse.getStatusLine().getStatusCode(); 
      String recode = String.valueOf(code); 
      HttpEntity entity = httpResponse.getEntity(); 
      is = entity.getContent(); 
      bufferedReader = new BufferedReader(new InputStreamReader(is)); 
      json_result = bufferedReader.readLine(); 

      try { 
       if (code == 200) { 

        JSONArray jsonArray = new JSONArray(json_result); 
        int length = jsonArray.length(); 
        for (int i = 0; i < length; i++) { 

         JSONObject c = jsonArray.getJSONObject(i); 

         String id = c.getString(TAG_ID); 
         String jobname = c.getString(TAG_JOBTITLE); 
         String description = c.getString(TAG_DESC); 
         String jobtype = c.getString(TAG_JOBTYPE); 
         String salary = c.getString(TAG_SALARY); 
         String postedon = c.getString(TAG_POSTEDDATE); 
         String location = c.getString(TAG_LOCATION); 
         String exp = c.getString(TAG_EXPE); 


         HashMap<String, String> result = new HashMap<String, String>(); 
         result.put(TAG_ID, id); 
         result.put(TAG_JOBTITLE, jobname); 
         result.put(TAG_DESC, description); 
         result.put(TAG_JOBTYPE, jobtype); 
         result.put(TAG_SALARY, salary); 
         result.put(TAG_POSTEDDATE,postedon); 
         result.put(TAG_LOCATION, location); 
         result.put(TAG_EXPE, exp); 


          resultList.add(result); 

        } 
       } else { 
        JSONObject jsonObj = new JSONObject(json_result); 
        status = jsonObj.getString("status"); 
        msg = jsonObj.getString("msg"); 
       } 
       return recode; 
      } catch (JSONException e) { 
       Log.e("Json erroe", e.toString()); 
       return e.toString(); 

Мой Json массив

[ 
    [ 
    { 
     "id": "30", 
    "title": "Android Design Engineer", 
     "description": "Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world", 
    "jobtype": "Contract", 
    "salary": " Upto $50", 
    "postedDate": "2016-11-19", 
    "location": "Alabama", 
    "experience": "2 to 6 yrs" 
    } 
    ], 
    [ 
    { 
     "id": "24", 
     "title": "Android Application Developer", 
     "description": "Android Application Developer is the major Development Technique that is used in this damn World.", 
    "jobtype": "Contract", 
    "salary": " Upto $50", 
    "postedDate": "2016-11-16", 
    "location": "North Carolina", 
    "experience": "6 to 10 yrs" 
     } 
    ] 
    ] 
+0

Это правильное значение Json на вашем сервере? –

+0

загляните в мой обновленный вопрос –

+0

Этот дизайн данных JSON не подходит для мобильных сервисов потребления. Он создает проблемы с памятью для низкоуровневых устройств. –

ответ

1

Проверьте ниже разборе логики, как в вашем JSON:

try { 
       HttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail"); 
       httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       HttpResponse httpResponse = httpClient.execute(httpPost); 
       int code = httpResponse.getStatusLine().getStatusCode(); 
       String recode = String.valueOf(code); 
       HttpEntity entity = httpResponse.getEntity(); 
       is = entity.getContent(); 
       bufferedReader = new BufferedReader(new InputStreamReader(is)); 
       json_result = bufferedReader.readLine(); 

       try { 
        if (code == 200) { 
         JSONArray jsonArray = new JSONArray(json_result); 
         if (jsonArray != null && jsonArray.length() > 0) { 
          for (int i = 0; i < jsonArray.length(); i++) { 
           JSONArray jsonChildArray = jsonArray.getJSONArray(i); 
           if (jsonChildArray != null && jsonChildArray.length() > 0) { 
            JSONObject c = jsonChildArray.getJSONObject(0); 

            String id = c.getString(TAG_ID); 
            String jobname = c.getString(TAG_JOBTITLE); 
            String description = c.getString(TAG_DESC); 
            String jobtype = c.getString(TAG_JOBTYPE); 
            String salary = c.getString(TAG_SALARY); 
            String postedon = c.getString(TAG_POSTEDDATE); 
            String location = c.getString(TAG_LOCATION); 
            String exp = c.getString(TAG_EXPE); 


            HashMap<String, String> result = new HashMap<String, String>(); 
            result.put(TAG_ID, id); 
            result.put(TAG_JOBTITLE, jobname); 
            result.put(TAG_DESC, description); 
            result.put(TAG_JOBTYPE, jobtype); 
            result.put(TAG_SALARY, salary); 
            result.put(TAG_POSTEDDATE, postedon); 
            result.put(TAG_LOCATION, location); 
            result.put(TAG_EXPE, exp); 


            resultList.add(result); 
           } 
          } 
         } 
        } else { 
         JSONObject jsonObj = new JSONObject(json_result); 
         status = jsonObj.getString("status"); 
         msg = jsonObj.getString("msg"); 
        } 
        return recode; 
       } catch (JSONException e) { 
        Log.e("Json erroe", e.toString()); 
        return e.toString(); 
       } 
      } catch (Exception e) { 
       Log.e("erroe", e.toString()); 
       return e.toString(); 
      } 
+1

Здесь Основная логика синтаксического анализа - это основной JSONArray, который вы должны зацикливать и получить дочерний JSONArray, и каждый дочерний JSONArray имеет только один JSONObject. Этот JSONObject, который вы должны использовать для своего элемента listview, добавьте его в arraylist. –

+0

Супер ответ от @Ready Android, Спасибо, что помогли моему парню. –

0

Да .Есть является error.Your JSON данных имеет массив внутри массива и вы пытаются назначить внутренний массив как объект.

Первый конвертировать внешнюю массив JsonArray jsonArray1;

Итерации через этот массив. i = 0 -> jsonArray1.length; и создать другой

JsonArray jsonArray2 = jsonArray1 [i];

И, наконец, перебрать jsonArray2: J = 0 -> jsonArray2.length()

и создать JSONObject JSON = jsonArray2 [J];

Надеюсь, вы поняли. Это psuedocode. Если вы хотите код, скажите мне. Я могу его написать.

Смежные вопросы