java webサービス DTO⇒JSON

●ライブラリ

・Jacksonを使用する

参考URL:http://qiita.com/takehiro224/items/6db2841c0abbf4ffb233

 

DTO

package pack;

public class Info {
public String code;
public String name;
}

 

サーブレット

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

response.setContentType("applicaton/json;charset=UTF-8");
PrintWriter out = response.getWriter();

// ユーザ名
String user = "XXX";
// パスワード
String pass = "XXX";
// サーバ名
String servername = "localhost";
// SID
String sid = "XE";

Connection conn = null;
Statement stmt = null;
ResultSet rset = null;

try {

// JBBCドライバクラスのロード
Class.forName("oracle.jdbc.driver.OracleDriver");

// Connectionの作成
conn = DriverManager.getConnection("jdbc:oracle:thin:@" + servername + ":1521:" + sid, user, pass);

// Statementの作成
stmt = conn.createStatement();

// Resultsetの作成
rset = stmt.executeQuery("select CODE, NAME from FAMILY");

// ResultSetの件数取得
int count = 0;
while (rset.next()) {
count++;
}

// ResultSet → DTO
Info[] info = new Info[count];
int index = 0;
while (rset.next()) {
Info row = new Info();
row.code = rset.getString("CODE");
row.name = rset.getString("NAME");
info[index] = row;
index++;
}

// DTOJSON文字列
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);

out.println(json);

} catch (ClassNotFoundException e) {
//throw e;
} catch (SQLException e) {
//throw e;
} catch (Throwable e) {
throw e;
} finally {
try {
/* クローズ処理 */
if (rset != null) {
rset.close();
rset = null;
}

if (stmt != null) {
stmt.close();
stmt = null;
}

if (conn != null) {
conn.close();
conn = null;
}
} catch (Throwable e) {
// nop
}
}
}

 

●Jacksonを使用せず、JSON文字列の作成

// 取得したデータを出力する
// JSON 文字列の書き込み
out.println("\"employees\":[");
while (rset.next()) {
out.println("{\"code\" : \"" + rset.getString("CODE") + "\"," + "\"name\" : \"" + rset.getString("NAME") + "\"}");
}
out.println("]");