2

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.

2
  • What structure do you expect for your JSON object? Commented Apr 13, 2017 at 7:46
  • @TimBiegeleisen Hi. What do you mean by structure? Can I show you the "ideal" output of my JSON output? It looks like this "AppData": {"message": " ", "status": "success", "token": "****"} Commented Apr 13, 2017 at 7:56

1 Answer 1

2

Use GSON Download the following Google's API Gson

String json=new Gson().toJson(appdatas);
Sign up to request clarification or add additional context in comments.

4 Comments

Hi @BasilBattikhi I trying your code and it shows error. Should the GSON be Gson?
Check my updated answer Also don't forget to import Gson lib
Hi @BasilBattikhi Can you kindly check my updated question? Will JSon object able to do that?
Yep, but make sure you are not using simple json jar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.