从结果集中重新列出数据并转换为JSON

时间:2017-05-04 12:03:45

标签: arrays json postgresql rest resultset

我是json的新手。我想从ResultSet中获取所有值并将其设置为正确的JSON格式。我没有得到它如何解决这个问题。我已经尝试过stackoverflow中的很多东西,但我无法解决这个问题。请任何人帮我摆脱这个。

String query = "SELECT emp_id, code, salary  FROM emp_tbl";
ResultSet rs = stmt.executeQuery(query);
ArrayList<String> list = new ArrayList<String>();
while (rs.next()) {
    emp_id = rs.getString("emp_id");
    code = rs.getString("code");
    salary = rs.getString("salary");

    list.add("emp_id");
    list.add("code");
    list.add("salary");
    jsonarray = new JSONArray(list);
}
System.out.println("jsonarray: "+jsonarray);

这是输出:

jsonarray: ["1","5563","11000", "2","5463","14000", "3","9847","9000"]

但它应该是这样的

[
  {
    "emp_id": "1",
    "code": "5563",
    "salary": 11000
  }, {
    "emp_id": "2",
    "code": "5463",
    "salary": 14000
  }
]

如果我试过这个

while (rs.next()) {                 
    emp_id = rs.getString("emp_id");
    code = rs.getString("code");
    salary= rs.getString("salary");
    jsonarray.put("emp_id");
    jsonarray.put("code ");
    jsonarray.put("salary");
} 
System.out.println("jsonarray: "+jsonarray); 

然后输出

jsonarray: {"emp_id":"5","code":"526","salary":"10000"}

它只获得最后一行,但不是所有值。

2 个答案:

答案 0 :(得分:0)

来自Oracle文档http://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html

   JsonArray arr = Json.createArrayBuilder()
             .add(Json.createObjectBuilder()
                 .add("type", "home")
                 .add("number", "212 555-1234"))
             .add(Json.createObjectBuilder()
                 .add("type", "fax")
                 .add("number", "646 555-4567"))
             .build();

   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   JsonWriter writer = Json.createWriter(baos);
   writer.writeArray(arr);
   writer.close();

   String str = baos.toString();

生成此输出:

[{&#34; type&#34;:&#34; home&#34;,&#34; number&#34;:&#34; 212 555-1234&#34;},{&#34; type&#34 ;:&#34;传真&#34;,&#34;号码&#34;:&#34; 646 555-4567&#34;}]

答案 1 :(得分:0)

从查询中返回json对象数组:

select json_agg(row_to_json(emp_tbl)) as my_json
from (values
    ('1','5563',11000),
    ('2','5463',14000)      
) emp_tbl (emp_id, code, salary)
;
                                          my_json                                           
--------------------------------------------------------------------------------------------
 [{"emp_id":"1","code":"5563","salary":11000}, {"emp_id":"2","code":"5463","salary":14000}]