Reputation: 41
I am getting a json string as ["A","B","C","D","E"] in serlvet controller.
I want to convert this string into a Java string array. The Json string also includes [].
output should be a Java String array:
arr[0] = A
arr[1] = B
and so on. Could you please suggest a parsing solution?
Upvotes: 1
Views: 5338
Reputation: 73241
Using a stream you could convert it like so:
String s = "[\"A\",\"B\",\"C\",\"D\",\"E\"]";
String[] arr = Arrays.stream(s.substring(1, s.length()-1).split(","))
.map(e -> e.replaceAll("\"", ""))
.toArray(String[]::new);
You could also use a JSON library (which might be the prefered way). For example using Jackson:
String s = "[\"A\",\"B\",\"C\",\"D\",\"E\"]";
ObjectMapper mapper = new ObjectMapper();
String[] arr = mapper.readValue(s, String[].class);
Upvotes: 3
Reputation: 328
ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
}
return stringArray;
}
Upvotes: 0