0

I am parsing the json array and fetching the result. I want to store the json array values to string array.

Here is my code:

public static void main(String[] args) 
                throws JSONException, IOException, URISyntaxException 
{
    String[] Stage_Probability;
    JSONArray stagearray = x.getJSONObject(j).getJSONArray("val");
    Map<String, String> test2 = new HashMap<String, String>();
    for (j = 0; j < stagearray.length(); j++) 
    {
        test2.put(stagearray.getJSONObject(j).getString("pbty"), stagearray.getJSONObject(j).getString("sortorder"));
        System.out.println("----" + stagearray.getJSONObject(j).getString("pbty"));

        Stage_Probability[j] = stagearray.getJSONObject(j).getString("pbty").toString();
    }
}

It prints null. Any help will be appreciated.

Hussein El Feky
  • 6,627
  • 5
  • 44
  • 57
Arun Kumar
  • 21
  • 1
  • 2
  • 3

2 Answers2

1

Simple implementation:

    /* The JSONArray object comes in the form
     [{"accountNumber":"5626-72838-7377"},{"accountNumber":"5626-5555-7377"}]
     The algorithm below converts it to numerically indexed String[] array i.e
    {5626-2838-7377,5626-5555-7377}*/

   private static String[] jsonArrayToStringArray(JSONArray jsonArray) {
      int arraySize = jsonArray.size();
      String[] stringArray = new String[arraySize];
      for (int i = 0; i < arraySize; i++) {
        JSONObject jsonobj = (JSONObject) jsonArray.get(i);
        stringArray[i] = jsonobj.get("someObjectKey").toString();
      }
    return stringArray;
}
Amos Kosgei
  • 877
  • 8
  • 14
0

You just can use the code like this:

JSONArray array = new JSONArray(yourResponse);
List<String> list = new ArrayList<String>();
for (int i = 0; i < array.length(); i++){
    list.add(array.getJSONObject(i).getString("name"));
}
Ihor Dobrovolskyi
  • 1,241
  • 9
  • 19