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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With