Tan Yih Wei Tan Yih Wei - 4 months ago 44
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;
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stat = conn.createStatement();
String sql = "SELECT * FROM testdata";
ResultSet resu = stat.executeQuery(sql);
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));

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 Source

Use GSON Download the following Google's API Gson

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