View Full Version : [ask] insert data from database into JSON

10 May 2010, 9:00 PM
Hi all..
I want to ask how to insert data from database into JSON object..
that JSON will be used to populate data into combo box ext js...

here is the code :

<%@ taglib prefix="json" uri="http://www.atg.com/taglibs/json" %>

<%@ page import="java.sql.*"
import ="org.json.*"


class tes
String q="qq";
public void setQ(String q)
this.q = q;

public String getQ()
return q;

String x="";

tes obj = new tes();

String url = "jdbc:postgresql://localhost/Kiki";
String user = "postgres";
String pass = "kiki";
Connection con = DriverManager.getConnection(url, user, pass);
Statement stmt = con.createStatement();

String q = "select id, genre from genres";
ResultSet rs;
ArrayList list = new ArrayList();
//JSONArray root=new JSONArray();
x = rs.getString(2);
//String myOut1 = root.toString().replaceAll("'", " ");
String myOut = "{root:" + list + "}" ;

<json:array name="root" var="root" items="root">
<json:property name="genre" value="qq"/>

i'm confused how to passing jsp variable into value in json:object...

please tell me how to do it...
thx b4..

Mike Robinson
11 May 2010, 6:56 AM
(Trying to) read through your code, it looks to me like you're building the JSON-string "brute force," using simple string concatenation in the next-to-last line.

Well, it looks like you started to use JSON-formatting objects (from json.org), then abandoned the attempt...

You really do want to use a JSON-helper library (it could be the one you used or any of a half-dozen others), and do it exactly as prescribed. You want to construct a Java object that represents your entire result ... of which the "root" is simply one element (consisting of an array of objects). Do the entire task using Java objects, and within that, arrays of Java objects. Then, the very last thing that you do is to stuff that Java object through a suitable JSON encoder for transmission.

Generally speaking, on both the client side and the host side, you want to think of everything in the context of "the native language," be it (in this case) JavaScript or Java. JSON is simply an encoding/decoding step that you must go through. If you find yourself twiddling strings directly, I think "you're doing something wrong."