473,888 Members | 1,453 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterate through JSON object that is returned in response

1 New Member
I have the following question:
Im doing a sample application using dojo and json.

I have 2 classes:
1. Book class
package com.esolaria.do joex;

Expand|Select|Wrap|Line Numbers
  1. import org.json.JSONObject;
  2. import org.json.JSONException;
  4. public class Book {
  6.     private int bookId;
  7.     private String title;
  8.     private String isbn;
  9.     private String author;
  12.     public Book(int bookId, String title, String isbn, String author) {
  13.         this.bookId = bookId;
  14.         this.title = title;
  15.         this.isbn = isbn;
  16.         this.author = author;
  17.     }
  20.     public void setBookId(int bookId) {
  21.         this.bookId = bookId;
  22.     }
  23.     public int getBookId() {
  24.         return this.bookId;
  25.     }
  27.     public void setTitle(String title) {
  28.         this.title = title;
  29.     }
  30.     public String getTitle() {
  31.         return this.title;
  32.     }
  34.     public void setIsbn(String isbn) {
  35.         this.isbn = isbn;
  36.     }
  37.     public String getIsbn() {
  38.         return this.isbn;
  39.     }
  41.     public void setAuthor(String author) {
  42.         this.author = author;
  43.     }
  44.     public String getAuthor() {
  45.         return this.author;
  46.     }
  48.     public String toJSONString() throws JSONException {
  49.         JSONObject jsonObj = new JSONObject();
  50.         jsonObj.put("bookId", new Integer(this.bookId));
  51.         jsonObj.put("title", this.title);
  52.         jsonObj.put("isbn", this.isbn);
  53.         jsonObj.put("author", this.author);
  54.         return jsonObj.toString();
  55.     }
  57. }
2. BookManager class.

Expand|Select|Wrap|Line Numbers
  1. package com.esolaria.dojoex;
  3. import java.util.ArrayList;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. import org.json.JSONObject;
  7. import org.json.JSONException;
  9. public class BookManager {
  11.     private static List books = new ArrayList();
  12.     static {
  13.         books.add(new Book(1, "Crime and Punishment", "0679734503", "Fyodor Dostoevsky"));
  14.         books.add(new Book(2, "The Collected Tales of Nikolai Gogol", "0375706151", "Nikolai Gogol"));
  15.         books.add(new Book(3, "King Rat", "0440145465", "James Clavell"));
  16.         books.add(new Book(4, "The Alchemist", "0062502182", "Paulo Coelho"));
  17.         books.add(new Book(5, "A Tale of Two Cities", "0451526562", "Charles Dickens"));
  18.     }
  21.     public static Book getBook(int bookId) {
  22.         Book returnValue = null;
  23.         for (Iterator iter = books.iterator(); iter.hasNext();) {
  24.             Book book = (Book) iter.next();
  25.             if (book.getBookId() == bookId){
  26.                 returnValue = book;
  27.                 break;
  28.             }
  29.         }
  30.         return returnValue;
  31.     }
  33.     public static List getAllBooks() {
  34.         books.size();
  35.         List book = BookManager.getBooks();
  36.         for(Iterator item = book.iterator(); item.hasNext();){
  37.             Book books = (Book) item.next();
  38.             System.out.println(books.getBookId());
  39.             System.out.println(books.getAuthor());
  40.             System.out.println(books.getIsbn());
  41.             System.out.println(books.getTitle());
  42.         }
  43.         return book;
  44.     }
  46.     public static List getBooks() {
  47.         return books;
  48.     }
  50. }

The middle layer is jsp: getAllBooks.jsp

Expand|Select|Wrap|Line Numbers
  1. <%@ page import="java.util.Iterator,
  2.          java.util.List,
  3.          com.esolaria.dojoex.Book,
  4.          com.esolaria.dojoex.BookManager" %>
  5. <%
  6.         List book = BookManager.getBooks();
  7.         for(Iterator item = book.iterator(); item.hasNext();){
  8.             Book books = (Book) item.next();
  9.             try{
  10.                 out.println(books.toJSONString());
  12.             }catch(Exception e){
  13.                 System.out.println(e);
  14.             }
  15.         }//for loop ends
  17. %>

My index file is having the following code:

[HTML]<%@ page
import="java.ut il.Iterator,
com.esolaria.do joex.Book,
com.esolaria.do joex.BookManage r" %>
<% List books = BookManager.get Books();%>
<title>Exampl e 1</title>
<script language="javas cript" src="../js/dojo/dojo.js"></script>
<script language="javas cript">
dojo.require("d ojo.io.*");
dojo.require("d ojo.event.*");
dojo.require("d ojo.html.*");

function trMouseOver(boo kId) {
getBookInfo(boo kId);

function trMouseOut(evt) {
//var bookDiv = document.getEle mentById("bookI nfo");
//bookDiv.style.d isplay = "none";

function getBookInfo(boo kId) {
//var params = new Array();
//params['bookId'] = bookId;
var bindArgs = {
url: "../actions/getAllBooks.jsp ",
error: function(type, data, evt){alert("err or");},
mimetype: "text/plain"
//content: params
var req = dojo.io.bind(bi ndArgs);
dojo.event.conn ect(req, "load", this, "populateDi v");

function populateDiv(typ e, data, evt) {

var result = "";
for(var i = 0; i < 5; i++){
var result += data.bookId +","+ data.title +","+ data.isbn +","+ data.author;


Hover over book title for more information.
<table border="1" cellspacing="1" cellpadding="3" style="backgrou nd-color:lavender; border: solid 1px #CCCCCC">
<% for (Iterator iter = books.iterator( ); iter.hasNext(); ) {
Book book = (Book) iter.next(); %>
<tr onmouseover="tr MouseOver(<%=bo ok.getBookId()% >)" onmouseout="trM ouseOut(<%=book .getBookId()%>) ">
<td><%=book.get Title()%></td><td></td>
<% } %>
<div id="bookInfo" style="display: none;"></div>


Im getting the response as a list but wanted to know how to iterate through that list to get the information of each individual book in seperate row of the table.

Thanks in advance.
Dec 22 '07 #1
4 8880
5,390 Recognized Expert Moderator Expert
hi ...

for that purpose you have to create the respective tr, td and textnodes and append it to the table ... you should use the:

- createElement() ;
- createTextNode( );
- appendChild();

dom-methods for this. have a look here ... there you find more information about dom-interfaces ...

kind regards
Dec 26 '07 #2
137 New Member
Wait a sec...is this the right forum to post this question? I was wondering why you were using "private" and "public" -- that's JAVA not JavaScript. Looks like you got your answer, but I wonder if this post shouldn't be moved to the Languages - JAVA forum instead.
Dec 26 '07 #3
5,390 Recognized Expert Moderator Expert
Wait a sec...is this the right forum to post this question? I was wondering why you were using "private" and "public" -- that's JAVA not JavaScript. Looks like you got your answer, but I wonder if this post shouldn't be moved to the Languages - JAVA forum instead.
it IS a javascript question ... have a look at the last part of the posted code :)

kind regards
Dec 26 '07 #4
137 New Member
it IS a javascript question ... have a look at the last part of the posted code :)

kind regards
LOL, I stopped reading after I saw the JAVA code. I gotta stop jumping to conclusions. :-)
Dec 26 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

by: asleepatdesk | last post by:
Hi, I need some help here. When I try to eval() my AJAX returned JSON string, I continually get a javascript error "Expected )". Here's my JSON string: {"recs": }; My js function simply tries to eval() it: var jsonStr = eval('(' + str + ')');
by: Tom Cole | last post by:
Let's say I have the following JSON string returned from a server-side process: { values: } I then create a JSON object from it using eval() (tell me if this is not what should be done). My question is this...how do I determine (without going through every single record) if there is a name=error in the values array?
by: dan.goyette | last post by:
I'm fairly new to using AJAX. I'm currently developing a data grid application in coldfusion, using AJAX for paging/filter/sorting updates to the grid. So far I've just been returning raw html, and updating the innerHTML of a div on the page when the response comes back. But now I've decided it would be useful to split my response into (at least) two parts. The first will be the raw HTML to place in the div. The second part will be...
by: Marc | last post by:
I'm aware that there are significant differences between VBScript objects and JScript objects but that doesn't mean something like the following should give me such troubles? <%@ Language=VBScript %> <script language="jscript" runat="server"> var json = {"widget":}; </script> <% Response.Write json.widget & "<br />"
by: dhtmlkitchen | last post by:
JSON We all know what it is. In ECMAScript 4, there's a JSON proposal: Object.prototype.toJSONString String.prototype.parseJSON The current proposal, String.prototype.parseJSON, returns an object.
by: RMWChaos | last post by:
Any JSON experts out there? I'd like to know if it is possible, and if so how, to iterate through a JSON property list so that each iteration selects the next value for each object. Here is an example list: function myFunction() { createDOM({ 'id' : , 'dom' : , 'parent' : "content", 'form' : ,
by: RMWChaos | last post by:
As usual, an overly-long, overly-explanatory post. Better too much info than too little, right? A couple weeks ago, I asked for some assistance iterating through a JSON property list so that my code would either select the next value in the member list or the single value. The original post can be found here. This is the code gits helped me write: for (var i = 0; i < attribList.id.length; i++) { var attrib = {};
by: Kelicula | last post by:
Hi all, I am usually a Perl programmer, I have some background in javascript and am attempting to create a Googleish selector div. Please bear with me, excuse the long introduction... Here's the details: Our site filters content by location. I use zip codes to find radius's. So if a user wants to see content from a location that they don't know the zip code for, I have set up this neat little input field that allows you to type the...
by: najmi | last post by:
hai.. i hava use FullCalendar in my application.i try to reload event into the calendar but it doesn`t work.here is my code <%@ page import="java.util.HashMap;" %> <%@ page import="java.util.Map;" %> <%@ page import="com.google.gson.Gson;" %>
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.