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,7075 gold badges49 silver badges59 bronze badges
asked Dec 23, 2016 at 12:13
Arun Kumar
211 gold badge2 silver badges3 bronze badges
-
Please show the json input.mad_manny– mad_manny2016年12月23日 12:19:46 +00:00Commented Dec 23, 2016 at 12:19
-
this line gives expected output.I want to save the output in one string array System.out.println("----" + stagearray.getJSONObject(j).getString("pbty"));Arun Kumar– Arun Kumar2016年12月23日 12:21:45 +00:00Commented Dec 23, 2016 at 12:21
2 Answers 2
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;
}
answered Jan 8, 2019 at 10:27
Amos Kosgei
9478 silver badges14 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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"));
}
answered Dec 23, 2016 at 13:00
Ihor Dobrovolskyi
1,24110 silver badges19 bronze badges
Comments
lang-java