无法获得预期的JSON格式

时间:2018-10-12 07:53:20

标签: java json servlets

我正在为html表创建JSON格式。但这似乎是我得到的格式错误。

下面是我的代码

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Gson gson=new Gson();

    Map<Object, Object> map = null;

        try {
            con = DBConnection.createConnection();
            statement = con.createStatement();
          String sql="SELECT HOUR(BILLTIME), SUM(NETAMOUNT) FROM SYNCBILL WHERE CANCELLED='N' AND BILLDATE BETWEEN '2018-08-01' AND '2018-08-31' AND OUTLET='S0001' GROUP BY HOUR(BILLTIME);";
            ResultSet  resultSet= statement.executeQuery(sql);

            while (resultSet.next()) {
                map = new TreeMap<Object, Object>();
                String xVal = resultSet.getString("HOUR(BILLTIME)");
                String yVal = resultSet.getString("SUM(NETAMOUNT)");
                map.put(xVal, yVal);




                System.out.println(map);
            }
    catch (SQLException e) {
        System.out.println("SQL Issues 2...");
        e.printStackTrace();
    }}

我希望我的json输出像

   [
    {
         "1": "454",
        "2": "554",
        "3": "111",
        "4": "45858",
        "5": "444",
        "6": "444",
        "7": "444",
         "8": "444",
        "9": "444",
         "10": "444"

     }

]

应将其括在数组中或[]大括号中的列表中

但是从我的代码中我会得到这样的结果

   {5=35942.0000}
{6=134923.3314}
{7=329324.0724}
{8=504761.6691}
{9=566401.2665}
{10=546588.2698}
{11=489917.3429}
{12=644758.5044}
{13=1108730.0100}
{14=1304635.6776}
{15=831015.3904}
{16=730210.3940}
{17=744253.6595}
{18=767145.8116}
{19=761547.2520}
{20=819265.4736}
{21=514267.8108}
{22=58592.0294}

我不知道我在哪里做错了,如果有人对此有所了解,请帮忙

1 个答案:

答案 0 :(得分:0)

您应该在循环外部创建地图,并在循环之后打印地图。