0

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?

Community
  • 1
  • 1
Choletski
  • 7,074
  • 6
  • 43
  • 64

2 Answers2

6

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.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • @Choletski You are welcome. BTW, from what I remember Android should have build in JSON parser, so you could try using it instead of gson. You may not be able to receive `String[] array` like here, but code like `jsonArray.get(0)` should also be fine. – Pshemo Aug 27 '15 at 14:09
0

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
La Machine
  • 363
  • 1
  • 8