简体   繁体   中英

convert json string to java string array

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?

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);
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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM