输入Hashmap <object,object =“”>进入JSONObject

时间:2017-04-13 07:44:16

标签: java mysql json

我有一个HashMap,用于存储数据库中的数据。如何将HashMap输入JSONObject?

HashMap<AppDataRequest, AppData> appdatas = new HashMap<AppDataRequest, AppData>();

public AppDataService(){
    Connection conn = null;
    Statement stat = null;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        stat = conn.createStatement();
        String sql = "SELECT * FROM testdata";
        ResultSet resu = stat.executeQuery(sql);
        while(resu.next()){
            int id = resu.getInt("app_id");
            String email = resu.getString("email");
            String password = resu.getString("password");
            String token = resu.getString("token");
            appdatas.put(new AppDataRequest(id, email, password), new AppData(" ", "success", token));
        }
        resu.close();
        stat.close();
        conn.close();
    }

如何将HashMap appdatas放入JSONObject?我尝试将HashMap放入JSONObject中,因为我希望实现如下输出。

{
"AppData": {
    "status": "success",
    "message": ""
    "token": "****"
  }
}

提前感谢您的回复。

1 个答案:

答案 0 :(得分:2)

使用GSON 下载以下Google的API Gson

String json=new Gson().toJson(appdatas);