Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT. Convert JSON string to String[]

Tags:

java

json

gwt

I have result JSON String: ['foo', 'bar', 'baz']. How I can convert it to String[] or JsArrayString? If it impossible what predefined data-structure I can use? I don't want to create my own class because it is redundant for simple string array.

like image 508
WelcomeTo Avatar asked Feb 19 '26 07:02

WelcomeTo


1 Answers

Since your string is a valid javascript array representation, you can use unsafeEval to get a javascript array:

JsArrayString a = JsonUtils.unsafeEval("['foo', 'bar', 'baz']");

Of course you have to be aware of security issues if you pass an arbitrary string to unsafeEval.

Otherwise, if your string were a valid JSON representation you could use safeEval instead which is more secure:

JsArrayString j = JsonUtils.safeEval("[\"foo\", \"bar\", \"baz\"]");

You can deal with JsArrayString easily in your java code, but if you prefer a java.lang.String[] you need to write some extra code like this (taken from the jscollections library). Note that in production mode the transformation doesn't add any performance penalty.

public static String[] toArray(JsArrayString values) {
  if (GWT.isScript()) {
    return reinterpretCast(values);
  } else {
    int length = values.length();
    String[] ret = new String[length];
    for (int i = 0, l = length; i < l; i++) {
      ret[i] = values.get(i);
    }
    return ret;
  }
}

private static native String[] reinterpretCast(JsArrayString value) /*-{
  return value;
}-*/;

Finally you can use java.util.List<String> as well, but it can have some performance issues.

List<String> l = Arrays.asList(s)
like image 145
Manolo Carrasco Moñino Avatar answered Feb 20 '26 19:02

Manolo Carrasco Moñino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!