How to convert java arraylist to javascript array? [duplicate]
How do we convert java array list of String objects to java script array?
This is what I am doing but I am looking for a better way to do it. I dont want to iterate over the array list.
var myArray = [
<c:forEach items="${myList}" var="item">
{itemName: "${item.name}"},
</c:forEach>
];
Thanks.
There is no direct way to convert the Java ArrayList to the Javascript Array.
You have to do one of the following step
1. Convert the Java ArrayList to the JSON String and then convert it to Javascript Array by parsing the String.
2. Directly write the ArrayList (using scriptlet) to the Javascript String and then split/parse it the the array.
3. Send a string by calling ArrayList.toString() as a response and then follow the Step 2.
var myArray2 = new Array();
myArray2= new Array('<s:property value="%{Listclassaveragelist}"/>');
var carter = myArray2.toString();
carter = carter.replace("[","");
carter = carter.replace("]","");
carter = carter.split(",");
You can use java libraries such as gson or Jackson to convert the arraylist object in java to JSON and then transfer it over to the client side where you can extract it from the JSON using javascript. Here you can avoid looping on the client side because gson converts java ArrayList to a javascript array when it creates JSON.
精彩评论