How to convert a JSONArray to an array of strings?

0
 String mensao = "[\"brega_falcao\",\"SamiPietikainen\",\"TecRahul\",\"gpantuza\",\"mkyong\",\"mkyong\",\"YouTube\"]";

Mensao is the JSONArray that I want to convert.

I tried this but it did not work:

//Retiro o '[' do inicio e do fim ']' do array json 
    String modificada = mensao.substring(1, mensao.length() - 1);


        List<String> lista = Arrays.asList(modificada);
        for (int i = 0; i < lista.size(); i++) {
            System.out.println(i + " " + lista.get(i));
        }

The problem is that it prints a big string and does not create an array of strings ... (that's what I sent the code to do, ma is not what we want ...)

Exit

0 "brega_falcao","SamiPietikainen","TecRahul","gpantuza","mkyong","mkyong","YouTube"

While this is what you want:

0 brega_falcao
1 SamiPietikainen
2 TecRahul
3 gpantuza
4 mkyong
5 mkyong
6 YouTube
    
asked by anonymous 17.04.2018 / 17:40

1 answer

1

You need to separate the String into smaller strings by the (",") tab before passing it to Arrays.asList(...) using the split(String) method. Also, you must remove the quotation marks:

String mensao = "[\"brega_falcao\",\"SamiPietikainen\",\"TecRahul\",\"gpantuza\",\"mkyong\",\"mkyong\",\"YouTube\"]";
String modificada = mensao.substring(1, mensao.length() - 1);

Arrays.stream(modificada.split(","))
        .map(s -> s.substring(1, s.length() - 1))
        .foreach(System.out::println);

To collect Stream as a array , you can use the toArray method. Example:

String[] strings = Arrays.stream(modificada.split(","))
                         .map(s -> s.substring(1, s.length() - 1))
                         .toArray(String[]::new);

An important note : This method works for the case you exemplify, but will not work properly if your Strings contains commas or spaces near the commas. If you need to take these issues into account, you'll need another solution, such as using regular expressions.

    
17.04.2018 / 18:10