2015-12-10 1 views
0

Я новичок в этом JSON, я пытаюсь получить значения JSON, на самом деле это как JSONArray без имени. Я просмотрел некоторые обучающие материалы, где они были доступны через JSONArray Keyword. Но в моем файле JSON нет такого ArrayName. Пожалуйста, помогите мне решить эту проблему. Это мой JSON Значение:Как получить JSONArray, у которого нет ключевого слова JSONArray в Android Studio

[ 
    {"id":"4","name":"Trichy"}, 
    {"id":"5","name":"Pondy"}, 
    {"id":"6","name":"Kovai"}, 
    {"id":"7","name":"Madurai"}, 
    {"id":"8","name":"Chennai"}, 
    {"id":"9","name":"Hyderabad"} 
    ] 

Мне нужно получить «имя» от этого. Вот мой файл MainActivity.

 try { 
      // Locate the NodeList name 
      JSONArray json=new JSONArray(???); //I dont know what to give here 
      for (int i = 0; i < json.length(); i++) { 
       jsonobject = jsonarray.getJSONObject(i); 

       Cites worldpop = new Cites(); 
       worldpop.setCity(jsonobject.optString("name")); 

       cit.add(worldpop); 

       // Populate spinner with country names 
       worldlist.add(jsonobject.optString("name")); 

      } 
     } catch (Exception e) { 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
     } 

Это мой файл City.java.

package com.example.user.spinnercontrol; 


public class Cites { 
private String city; 

public String getCity() 
{ 
    return city; 
} 
public void setCity(String city) 
{ 
    this.city=city; 
} 
} 

Это мой JSON.java файл (для справки)

package com.example.user.spinnercontrol; 
import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
    import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONCity { 

public static JSONObject getJSONfromURL(String url) { 
    InputStream is = null; 
    String result = ""; 
    JSONObject jArray = null; 

    // Download JSON data from URL 
    try { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 

    } catch (Exception e) { 
     Log.e("log_tag", "Error in http connection " + e.toString()); 
    } 

    // Convert response to string 
    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     result = sb.toString(); 
    } catch (Exception e) { 
     Log.e("log_tag", "Error converting result " + e.toString()); 
    } 

    try { 

     jArray = new JSONObject(result); 
    } catch (JSONException e) { 
     Log.e("log_tag", "Error parsing data " + e.toString()); 
    } 

    return jArray; 
} 
} 
+0

перед [] любой ИМЯКЛАВИШИ будет там ??? – curiousMind

+0

Нет ... Нет ключа для этого массива JSON. –

+0

только то, что много json есть ??? любая другая вещь не существует кроме этого? – curiousMind

ответ

0

MainActivity класс должен быть, как это ::

public class MainActivity extends Activity { 
JSONObject jsonobject; 
ArrayList<String> worldlist = new ArrayList<>(); 
ArrayList<Cites> cit = new ArrayList<>(); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    JSONArray arr = JSONCity.getJSONfromURL("http://www.prateektechnosoft.com/justcall/cities/getall"); 

    for (int i = 0; i < arr.length(); i++) { 

     try { 
      jsonobject = arr.getJSONObject(i); 

      Cites worldpop = new Cites(); 
      worldpop.setCity(jsonobject.optString("name")); 

      cit.add(worldpop); 

      // Populate spinner with country names 
      worldlist.add(jsonobject.optString("name")); 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

    } 

    Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner); 

    // Spinner adapter 
    mySpinner 
      .setAdapter(new ArrayAdapter<String>(MainActivity.this, 
        android.R.layout.simple_spinner_dropdown_item, 
        worldlist)); 

    // Spinner on item click listener 
    mySpinner 
      .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 

       @Override 
       public void onItemSelected(AdapterView<?> arg0, 
              View arg1, int position, long arg3) { 

       } 

       @Override 
       public void onNothingSelected(AdapterView<?> arg0) { 
        // TODO Auto-generated method stub 
       } 
      }); 


} 

} 
+0

Большое вам спасибо. Работает отлично. :) –

+0

@AnishKumar upvote мой ответ также – curiousMind

+0

Попытка вызвать виртуальный метод 'int org.json.JSONArray.length()' на ссылку нулевого объекта Я получаю эту ошибку сейчас. –

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