2017-04-13 11 views
2

私はデータベースからのデータを格納するHashMapを持っています。 HashMapをJSONObjectにどのように入力すればよいですか?入力Hashmap <Object、Object> 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(); 
    } 

JSONObjectにHashMap appdatasを配置するにはどうすればよいですか?私は以下のような出力を達成したいので、HashMapをJSONObjectに入れようとします。

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

お返事ありがとうございます。

+0

次のGoogleのAPIをダウンロードしますか? –

+0

@TimBiegeleisenこんにちは。あなたは構造によって何を意味しますか? JSON出力の「理想的な」出力を表示できますか? 「AppData」のように見えます:{"メッセージ": ""ステータス ":"成功 "、"トークン ":" **** "}' –

答えて

1

使用GSON あなたはJSONオブジェクトに期待しますどのような構造Gson

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

こんにちは@BasilBattikhiあなたのコードを試してみました。 。 'GSON'は' Gson'であるべきですか? –

+0

私の更新された回答を確認 また、Gsonのライブラリをインポートすることを忘れないでください –

+0

こんにちは@BasilBattikhi私の更新された質問を親切にチェックできますか? JSonオブジェクトはこれを実行できますか? –

関連する問題