1

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?

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Parsing JSON on your is risky in terms of security (especially in a web environment). Just use one of the well-known JSON libraries as GSON, Jackson, etc.
Right @jannis, added an example with jackson
0
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.