2016-11-13 2 views
-1

私はテーブルへの要求の結果としてResultSetオブジェクト を持っている:RestletフレームワークでResultSetをjsonオブジェクトに変換する方法は?

ResultSet result = stat.executeQuery("SELECT * FROM Greetings"); 

私はJSON形式でブラウザにそれを返す必要があります。いくつかのRestletツールを使用してResultSet型の変数をjsonオブジェクトに変換してWebクライアントに送信することは可能ですか?

+1

たぶん私は混乱しているが、[このリンク](HTTPSに見られるものを含むJSONへの変換のResultSetを扱うこのサイトには多くの質問が、あります。 //www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+resultset+to+json)。 –

答えて

3

resultSetをjsonArrayに変換してブラウザに送信するには、次の関数を使用できます。

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

private JSONArray convertToJSON(ResultSet resultSet) 
     throws Exception { 
    JSONArray jsonArray = new JSONArray(); 

    while (resultSet.next()) { 
     int total_rows = resultSet.getMetaData().getColumnCount(); 
     JSONObject obj = new JSONObject(); 
     for (int i = 0; i < total_rows; i++) { 
      obj.put(resultSet.getMetaData().getColumnLabel(i+1) 
        .toLowerCase(), resultSet.getObject(i + 1)); 
     } 
     jsonArray.put(obj); 
    } 

    return jsonArray; 
} 
+0

この回答が十分でないかどうか質問してください。私はあなたの要件に応じて私の答えを更新します。 –

0

/jackson/databind/ObjectMapperクラスを使用すると、JavaオブジェクトをJSONに変換できます。

ObjectMapper mapper = new ObjectMapper(); 

    Greetings greetings = new Greetings(); 

    //Object to JSON in file 
    mapper.writeValue(new File("c:\\file.json"), greetings); 

    //Object to JSON in String 
    String jsonInString = mapper.writeValueAsString(greetings); 

MavenのPOMの依存

<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
</dependency> 
関連する問題