1

I am rather new to JSON at the moment, but I need to convert a JSON response that contains the same key, but different values to an ArrayList to use it with my spinner.

I tried it like here: Converting JSONarray to ArrayList

But i get the whole json string, but just need the value part. I can't figure out how to do this and found no answer that worked for me :/

What I want would be a List like:

City1
City2
City3

But i have in my spinner:

{"city":"name1"}
{"city":"name2"}
{"city":"name3"}

Code I have is:

JSONArray obj = new JSONArray(response);

Spinner availableCitySpin;
availableCitySpin = (Spinner) findViewById(R.id.avCitySp);

List<String> cityValues = new ArrayList<String>();

if (jarr != null) {
  for (int i=0;i< jarr.length();i++){
    cityValues.add(jarr.getString(i).toString());
  }
}

ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this,
  android.R.layout.simple_spinner_item, cityValues);

cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
availableCitySpin.setAdapter(cityAdapter);
availableCitySpin.setSelection(0);
Community
  • 1
  • 1
boehmP
  • 91
  • 1
  • 1
  • 11

2 Answers2

1

Change your code to something like this:

...
for (int i=0;i< jarr.length();i++){
    JSONObject cityObject = jarr.getJSONObject(i);
    cityValues.add(cityObject.getString("city"));
}
...
Akivamu
  • 550
  • 5
  • 17
0

Try this:

  1. First use split For example: String[] result = splits[0].split(":");

you will get two item in array result. result[0]= {"city" and result[1] = "name1"}

  1. If you want to get the key use result[0]

remove sign from result[0] using replace. Example: data = result[0].replace("\"","").replace("{","");

use it in loop, should work

K.Sopheak
  • 22,904
  • 4
  • 33
  • 78