mysql—如何通过java或sql按数据库表中定义的顺序获取json?

xv8emn3q  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(292)

我正在计算json格式的数据,将其用作navbar。我已经做了json,但是在我的数据库表中有一列指定了菜单的顺序,所以我只想按这个顺序返回json。
我的数据库表如下所示:

我的java代码是:

String sql="select menu,submenu,link,menu_order from test1";
while(resultSet.next()) {
            String menu = resultSet.getString("menu");

            String subMenu = resultSet.getString("submenu");
            String link = resultSet.getString("link");

            map.compute(menu, (key, subMenus) -> {
                Map<String, String> mapSubMenu = new LinkedHashMap<>();
                mapSubMenu.put("type", subMenu);
                mapSubMenu.put("link", link);

                subMenus = subMenus != null ? subMenus : new ArrayList<>();

                //check for empty or null string otherwise return empty ArrayList
                if(!"".equalsIgnoreCase(subMenu) && !"".equalsIgnoreCase(link))
                 subMenus.add(mapSubMenu);

                return subMenus;
            });
            str = gson.toJson(map);
        }
        System.out.println(str);

我从这样的代码中得到json

{
  "India": [
    {
      "type": "delhi",
      "link": "https: //www.google.com"
    },
    {
      "type": "mumbai",
      "link": "https: //www.google.com"
    }
  ],
  "australia": [
    {
      "type": "sydney",
      "link": "https: //www.google.com"
    },
    {
      "type": "melbourn",
      "link": "https: //www.google.com"
    }
  ],
  "spain": [
    {
      "type": "valencia",
      "link": "https: //www.google.com"
    },
    {
      "type": "madrid",
      "link": "https: //www.google.com"
    }
  ],
  "logout": [

  ]
}

它是显示数据,因为它是在我的数据库表中,但我有一个列作为菜单的顺序,它定义了什么应该是菜单的顺序,并根据那里的子菜单将来。
如何在java端或查询端实现这一点?

gjmwrych

gjmwrych1#

您应该在查询中添加order by

String sql="select menu,submenu,link,menu_order from test1 ORDER BY menu_order";

相关问题