简体   繁体   中英

Convert JSON array[array[String]] to Java array

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?

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;
}

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()]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM