This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes HTML, CSS and JavaScript and the fly likes Reading a 'Collection' object from JSON Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Reading a Watch "Reading a New topic

Reading a 'Collection' object from JSON

Abhishek Asthana
Ranch Hand

Joined: Sep 08, 2004
Posts: 146

My class has following attributes:
String a;
int b;
ArrayList<String []> c;

I am converting it to JSON object.
jsonObj.put("a", this.a);
jsonObj.put("b", this.b);
jsonObj.put("c", this.c);

I am using Dojo and in my JSP I get the response back in JSON. For ordinary data types 'a' and 'b', it's fine.

But how to get the data that is enclosed in 'c'? How to traverse that collection and get the String[] values?

Please help me with this.

Frank Zammetti
Ranch Hand

Joined: Dec 16, 2004
Posts: 136
With the caveat that I haven't tried this code, it should just be:



for (var i = 0; i < data.c.length; i++) {

So long as your JSP rendered the JSON properly, the c should be an array, which you should be able to just access with simple array notation.

-- <br />Frank W. Zammetti<br />Founder and Chief Software Architect<br />Omnytex Technologies<br /><a href="" target="_blank" rel="nofollow"></a><br />AIM/Yahoo: fzammetti<br />MSN:<br />Author of "Practical Ajax Projects With Java Technology"<br /> (2006, Apress, ISBN 1-59059-695-1)<br />and "JavaScript, DOM Scripting and Ajax Projects"<br /> (2007, Apress, ISBN 1-59059-816-4)<br />Java Web Parts - <a href="" target="_blank" rel="nofollow"></a><br /> Supplying the wheel, so you don't have to reinvent it!
Abhishek Asthana
Ranch Hand

Joined: Sep 08, 2004
Posts: 146
Thanks Frank

That worked partially. My JSONString looks like this:

So when I do

It prints '[Ljava.lang.String;@128d1f4' rather than the value contained by this object. How do I get the value printed?

Frank Zammetti
Ranch Hand

Joined: Dec 16, 2004
Posts: 136
That *is* the value You have to implement some sort of meaningful toString() on the Java class you're marshalling, otherwise you get the typical, basic Java implementation.
I agree. Here's the link:
subject: Reading a 'Collection' object from JSON
Similar Threads
Can someone help me with the "new" dojo calls?
Problem with
Writing JSON data back to client
Ajax populated dropdown submitting improperly
Dojo populatig drop down before request comes from the server