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?

2
  • is it json that you are getting? Commented Aug 27, 2015 at 13:57
  • You have an array of strings and you want to convert it to an array of strings? It's not clear what you're asking. Could you add more details to your question? Commented Aug 27, 2015 at 13:58

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@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.
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

1 Comment

What if text contains nested [ or ] like ["foo","[bar]"]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.