Reputation: 6690
I have a JavaScript JSON array[array[String]] called jsonArray
in my JSP1.jsp
.
I am converting jsonArray
to a String jsonArrayStr
using JSON.stringify(jsonArray)
in JSP1.jsp
.
I am passing jsonArrayStr
as a parameter while calling another JSP JSP2.jsp
this way-
"JSP2.do?jsonArrayStr="+jsonArrayStr
In JSP2.jsp
, I am doing this-
String jsonArrayStr = request.getParameter("jsonArrayStr");
Now how do I convert jsonArrayStr
to Java array (JSP2.jsp
doesn't contain any JavaScript code)
Summary-
I have a JavaScript JSON Array in a JSP1.jsp
, which I want to access as a normal Java array/arraylist in JSP2.jsp
. How do I achieve this?
Upvotes: 2
Views: 6213
Reputation: 2400
OK, so you have a two-dimensional array of strings represented as a JSON like this stored in a Java String:
[["a", "b", "c"],["x"],["y","z"]]
You need to somehow parse or "deserialize" that value into a Java String[][]. You can use a library like from http://www.json.org/java/index.html or http://jackson.codehaus.org/ or you can try to do it manually. Manually could be a little tricky but not impossible. The json.org library is very simple and might be good enough. The code would be something like this (I haven't tried/tested this):
JSONArray jsonArray = new JSONArray(jsonArrayStr); // JSONArray is from the json.org library
String[][] arrayOfArrays = new String[jsonArray.length()][];
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray innerJsonArray = (JSONArray) jsonArray.get(i);
String[] stringArray = new String[innerJsonArray.length()];
for (int j = 0; j < innerJsonArray.length(); j++) {
stringArray[j] = innerJsonArray.get(j);
}
arrayOfArrays[i] = stringArray;
}
Upvotes: 1
Reputation: 15768
somethingk like this
ArrayList<String> strings= new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
String[] Stringarray = strings.toArray(new String[strings.size()]);
Upvotes: 0