Choletski
Choletski

Reputation: 7515

convert string ["string"] to string array

I have a kind of strange problem, I am receiving from server side an compressed text that is a string array, for exemple ["str1","str2"] or just ["str"]

Can I convert it to an normal string array? like:

 String[] array;
 array[1] = "str";

I know that is not a big deal to convert an simple string but not this one...Any ideas?

Upvotes: 0

Views: 2029

Answers (2)

Pshemo
Pshemo

Reputation: 124215

This text can be treated as JSON so you could try using JSON parser of your choice. For gson your code could look like.

String text = "[\"str1\",\"str2\"]"; // represents ["str1","str2"]

Gson gson = new Gson();

String[] array = gson.fromJson(text, String[].class);

System.out.println(array[0]); //str1
System.out.println(array[1]); //str2

If you are able to change the way server is sending you informations you can consider sending array object, instead of text representing array content. More info at

or many other Java tutorials under serialization/deserialization.

Upvotes: 6

La Machine
La Machine

Reputation: 363

This may help you:

    // cleanup the line from [ and ]
    String regx = "[]";
    char[] ca = regx.toCharArray();
    for (char c : ca) {
        line = line.replace("" + c, "");
    }

    String[] strings = line.split("\\s*,\\s*");

    // now you have your string array

Upvotes: 0

Related Questions