12

In my Java code, I have an ArrayList of Strings. I'd like to put this data in a JavaScript variable on a JSP page I'm working on. My first thought was to include it directly, e.g.:

var myArray = <%= arrayList %>;

Unfortunately, when executed, myArray is a string in the format [a,b,c], not an actual JavaScript array. How do I get some data from a Java ArrayList to a JavaScript array?

1
  • please add more code with an example data Commented Jul 3, 2013 at 5:21

6 Answers 6

13

Withoug a library:

Java:

public static String toJavascriptArray(String[] arr){
    StringBuffer sb = new StringBuffer();
    sb.append("[");
    for(int i=0; i<arr.length; i++){
        sb.append("\"").append(arr[i]).append("\"");
        if(i+1 < arr.length){
            sb.append(",");
        }
    }
    sb.append("]");
    return sb.toString();
}

JSP:

var myArray = <%= toJavascriptArray(arrayList) %>;
Sign up to request clarification or add additional context in comments.

1 Comment

Technique is good, but still you need to parse it to JSON, while assigning to javascript variable.
5

When you use <%=arraylist%> it calls the toString() on list and prints [a,b,c]

And No,you cannot direclty convert From Java arrayList to javascript array ,Convert the Java ArrayList to JSON String, and use JSON.parse() to get Javascript object.

Have a look at Json objet and Json in java

3 Comments

Thanks buddy. I have the json string like [a,b,c]. When i use Json.parse(aa); It shows the error. Uncaught reference error.a is not defined. So it must be like ["a","b","c"]. So how to convert like this?
Dude,you have to add json library to your class path and convert your arraylist on serverside to json string and send it to client.Then JSON.parse() works :)
The second link in the answer is not available anymore.
2

Do the following in your JSP page

<% List<String> strList = new ArrayList<String>();
strList.add("one");
strList.add("two");
strList.add("three"); %>

var jsArray = [<% for (int i = 0; i < strList.size(); i++) { %>"<%= strList.get(i) %>"<%= i + 1 < strList.size() ? ",":"" %><% } %>];

The output will be

var jsArray = ["one","two","three"];

If your List was empty it will output

var jsArray = [];

Comments

2

The JavaScript split() method returns an array, so it's a simple way to convert a Java ArrayList into a JavaScript array.

function toJavascript(){
    var array="<%=javaArrayList%>";
    array=array.replace("[", "");
    array=array.replace("]", "");
    return javaArray.split(",");
}

Comments

1

try this way:

var myArray = <%=net.sf.json.JSONSerializer.toJSON(arrayList) %>;

Comments

0

Simple

 var jsArray = JSON.parse(yourJavaListObject)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.