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.
2 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)
2 Comments
GWT actually has built in classes for working with JSON in the com.google.gwt.json.clint package. Note that you'll need to add
<inherits name="com.google.gwt.json.JSON" />
to your gwt.xml file.
JSONArray array = JSONParser.parseLenient("['foo', 'bar', 'baz']").isArray();
String[] resultArray = String[array.size()];
for(int i = 0; i < array.size(); i++)
resultArray[i] = array.get(i).isString().stringValue();