简体   繁体   中英

Android parse Json array of Strings

How can I parse in Android a Json array of strings and save it in a java string array ( like: xy[ ] ) ?

My Json to be parsed :

 [
  {
    "streets": [ "street1", "street2", "street3",... ],
  }
 ]

Later in my code I want to populated with that array a spinner item in my layout. Everything i tried enden with only one street item listed in the spinner.

To parse

try {

   JSONArray jr = new JSONArray("Your json string");
   JSONObject jb = (JSONObject)jr.getJSONObject(0);
   JSONArray st = jb.getJSONArray("streets");
   for(int i=0;i<st.length();i++)
       {
      String street = st.getString(i);
      Log.i("..........",""+street);
      // loop and add it to array or arraylist
        }
}catch(Exception e)
{
        e.printStackTrace();
}

Once you parse and add it to array. Use the same to populate your spinner.

[ represents json array node

{ represents json object node

Try this..

 JSONArray arr = new JSONArray(json string);

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

            JSONObject c = arr.getJSONObject(i);        
            JSONArray ar_in = c.getJSONArray("streets");

        for(int j = 0; j < ar_in.length(); j++){    
            Log.v("result--", ar_in.getString(j));
        }
   }

We need to make JSON object first. For example,

JSONObject jsonObject = new JSONObject(resp);
// resp is your JSON string
JSONArray arr  = jsonObject.getJSONArray("results");
Log.i(LOG, "arr length =  " + arr.length());
for(int i=0;i<arr.length();i++)
{...

arr may contains other JSON Objects or JSON array. How to convert the JSON depends on the String. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM