kittu
kittu

Reputation: 7018

ResultSet to Json in java servlet

Trying to get data from database and storing in JSON object as below:

try {
            JsonObject jsonResponse = new JsonObject();
            JsonArray data = new JsonArray();
            JsonArray row = new JsonArray();
            PrintWriter out = response.getWriter();

            Connection con = OracleDBConnection.getConnection();
            String query = "Select * from CUSTOMER_DEMOGRAPHICS";
            Statement st = con.createStatement();
            ResultSet rSet = st.executeQuery(query);

            while (rSet.next()) 
            {
                row.add(new JsonPrimitive(rSet.getString("COUNTRY")));
                row.add(new JsonPrimitive(rSet.getString("STATE")));
                row.add(new JsonPrimitive(rSet.getString("CITY")));
                data.add(row);
            }

            jsonResponse.add("ResponseData", data);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            out.print(jsonResponse);
            out.flush();
            System.out.println(jsonResponse);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Table structure in database:

COUNTRY     STATE       CITY
================================
AUSTRALIA   VICTORIA    MELBOURNE
AUSTRALIA   NEW SOUTH   SYDNEY

The problem is when I print the json, it prints twice for each row as follows rather than once.

{ "ResponseData": [["AUSTRALIA","VICTORIA","MELBOURNE","AUSTRALIA ","NEW SOUTH WALES","SYDNEY"], ["AUSTRALIA","VICTORIA","MELBOURNE","AUSTRALIA ","NEW SOUTH WALES","SYDNEY"]] }

Upvotes: 0

Views: 3350

Answers (2)

Amr Morgan
Amr Morgan

Reputation: 1

i think the you should add this code to the start of while()

row = new JsonArray();

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691805

You're creating a single row, and adding it twice to the array. The line

JsonArray row = new JsonArray();

should be inside the loop. Not outside.

Upvotes: 2

Related Questions