0

I have a

ResultSet rs = sql.getData(con, query);

with two columns and several rows. I want to get the data as a output in a JSON style output like:

x: [1, 2, 3, 4],

y: [2.37, 2.16, 4.82, 1.73],

So, I want first the data of column1 written to the first line "x" and then the second column2 to y.

All documentation I find about iterating the data of a resultset is row-wise like for the HTML table output like

    while (rs.next()) {
        out.append("<tr>");
        for (int col = 1; col < rsMeta.getColumnCount() + 1; col++) {
            out.append("<td>");
            out.append(rs.getString(col));
            out.append("</td>");
        }
        out.append("</tr>");
        cnt++;
    }
5
  • How about you try to write some code for JSON creation first? Commented Oct 6, 2016 at 7:09
  • You're talking about JSON but in your code you create XML (in a very naive manner). Do you want XML or JSON? For both you should use a library instead of creating the output format as text. Commented Oct 6, 2016 at 7:18
  • I do not want to create a JSON object in Java I just want to output it for a webapp in a JSON way. I already tried the library json-simple but could not make it output the way I wanted. Commented Oct 6, 2016 at 7:21
  • Use two lists, one for each column. Iterate through the records and store the values for each column to the appropriate list. At the end create the output by iterating over each list one after another. This works only for small datasets, because you have to store the whole data in memory. Commented Oct 6, 2016 at 7:25
  • These libraries are exactly made for the purpose to create output in JSON or XML format. Because doing it by hand is error prone. You have to consider all special cases, escaping, etc. And sorry, but looking at your code, you seem to be even unaware about the difference between XML and JSON. Commented Oct 6, 2016 at 7:31

1 Answer 1

1

You need to iterate the ResultSet exactly once, but since you want the values by column, not by row, you need to store them in List objects.

Something like this:

List<Integer> x = new ArrayList<>();
List<Double> y = new ArrayList<>();
while (rs.next()) {
    x.add(rs.getInt(1));
    y.add(rs.getDouble(2));
}
System.out.println("x: " + x + ",");
System.out.println("y: " + y + ",");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.