Tan Yih Wei Tan Yih Wei - 14 days ago 13
JSON Question

Input Hashmap<Object, Object> Into JSONObject

I have a HashMap which store data from database. How do I input the HashMap into 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();
}


How do I put the HashMap appdatas into JSONObject? I try to put the HashMap into JSONObject because I wish to achieve the output as below.

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


Thank in advance for any reply.

Answer

Use GSON Download the following Google's API Gson

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