How to convert a Jsonarray to a Strings array?

Asked

Viewed 117 times

0

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

Mensao is the Jsonarray I want to convert.

I tried that but it didn’t 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 doesn’t create an array of strings...(that’s what I told the code to do, but that’s not what we want...)

Exit

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

As long as that’s what you want:

0 brega_falcao
1 SamiPietikainen
2 TecRahul
3 gpantuza
4 mkyong
5 mkyong
6 YouTube

1 answer

1


You need to separate the String greater in Strings smaller by the separator (",") before passing it to the Arrays.asList(...) using the method split(String). Also, you should remove the quotes:

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 the Stream as a array, you can use the method toArray. Example:

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

An important observation: this method works for the case exemplified by you, but it will not work properly if your Strings contain commas or in case of spaces near commas. If you need to take these problems into account, you will need another solution, as through the use of regular expressions.

  • Thanks, but as I can return a String Array instead of printing, you can add this function to your reply?

  • @Painted penada When you say "array", you actually say a array or a list (as in the example of your question)?

  • String[] string = new String[size];

  • @Penapintada Added in the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.