Passing arrays

Hi gurus,

From a servlet I have the following 2D array example:

String myPoints = new String[5];
ArrayList myPointList = new ArrayList();

int i=0;
while i<2 {
request.setAttribute(“myarray”, myPointList);

From the JSP, I am calling:

var test = ‘${myarray}’;

When I view the source code of the result page, what I want to see is [{“zero”, “one”}, {“zero”, “one”}] but instead I see [[Ljava.lang.String;@44f787, [Ljava.lang.String;@44f787].

Can anyone tell me how to fix this? Many thx in advance…

Because the toString on any array will return something like this Ljava.lang.String;@44f787. The toString on ArrayList returns the a more readable list. So if myPoints was an ArrayList instead of a String this will work. Otherwise you need to actually loop through array values.

Thank you very much for the quick response. :slight_smile:

If I use your solution, the result I get is [[“zero”, “one”], [“zero”, “one”]];

I need for the inner brackets to be curly braces: ie [{“zero”, “one”}, {“zero”, “one”}];

How can I do this?

If you’re doing this to dynamically produce values for javascript, use a json library if you want something robust.

You might need to write a for loop inside of your JSP to get the desired formatting.

OR, you need to extend ArrayList and implement the toString() method yourself to get the formatting that you desire. I personally don’t think that overriding the toString() method for view purposes is a good idea, but in this case it might be what you need.

I would agree, if you’re attempting to perform output for Javascript in JSON form, consider using on of the many json libraries out there.

I believe I used SimpleJSON (there are two different projects with the same name) with some success.

You guys have been a tremendous help, thank you :slight_smile:

I just have one last question concerning JSON in general because google has not been kind :injured:

It seems that any forward slash character is treated as an escape character. So, if I have value “a/b/c” JSON will spit it out as “a\/b\/c”. I’ve tried creating a class and overwriting the toJSONString method using the replace method to no avail… is there any quick way to not have that “\” character thrown into the string?

Not sure, I’m sure it depends on the library you’re using.

However, if you’re using a compatible Javascript JSON library to read the returned output from your server, those slashies should go away.

you could also do data munging on the client side with javascript and replace all \/ with /. But that might get ugly quickly.