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.

share|improve this question
1  
Tried anything? – BoltClock Sep 29 '11 at 5:19
How are you getting the data structure out of java and into javascript? – Cory Kendall Sep 29 '11 at 5:22
Please see I have updated my question. – anything Sep 29 '11 at 5:23
feedback

3 Answers

up vote 2 down vote accepted

Refer to this link

share|improve this answer
Hi Thanks for the reply. This is what I am currently doing. I am looping over my array list and converting it to java script array. This is working form me but is there any way I dont have to iterate over the list. – anything Sep 29 '11 at 5:27
According to my knowledge if you want to build an array in Client side you should use looping – Sai Kalyan Akshinthala Sep 29 '11 at 5:30
feedback

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.

share|improve this answer
4. Output a JS array literal from JSP (similar to the code in the question; there doesn't have to be a step where you convert it to a string and then parse the string). – nnnnnn Sep 29 '11 at 6:26
feedback

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.

share|improve this answer
1  
json-lib.sourceforge.net is another alternative – Arun P Johny Sep 29 '11 at 5:40
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.