アクションからの呼び出し例
@Execute(validator = false)
public String hello() {
Map<String, Object> json = new HashMap<String, Object>();
json.put("author", "Goldratt & Fox");
json.put("title", "The Race");
JSONResponseUtil.writeJSON(json);
return null;
}ユーティリティの実装
package net.naruh.sastruts.util;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.servlet.http.HttpServletResponse;
import net.arnx.jsonic.JSON;
import org.seasar.framework.exception.IORuntimeException;
import org.seasar.struts.util.RequestUtil;
import org.seasar.struts.util.ResponseUtil;
/**
* JSONをレスポンスに書き出すためのユーティリティクラスです。
* @author hnakamur
*/
public final class JSONResponseUtil {
/** JSONのエンコーディング */
public static final String JSON_ENCODING = "UTF-8";
/** JSONのコンテントタイプ */
public static final String JSON_CONTENT_TYPE = "application/json";
/**
* JSONをレスポンスに書き出します。
* @param source 書き出すオブジェクト
* @param prettyPrint 出力を整形するか
*/
public static void writeJSON(Object source) {
writeJSON(source, false, JSON_CONTENT_TYPE, null);
}
/**
* JSONをレスポンスに書き出します。
* @param source 書き出すオブジェクト
* @param prettyPrint 出力を整形するか
*/
public static void writeJSON(Object source, boolean prettyPrint) {
writeJSON(source, prettyPrint, JSON_CONTENT_TYPE, null);
}
/**
* JSONをレスポンスに書き出します。
* @param source 書き出すオブジェクト
* @param prettyPrint 出力を整形するか
* @param contentType コンテントタイプ
*/
public static void writeJSON(Object source, boolean prettyPrint, String contentType) {
writeJSON(source, prettyPrint, contentType, null);
}
/**
* JSONをレスポンスに書き出します。
* @param source
* 書き出すオブジェクト
* @param prettyPrint
* 出力を整形するか
* @param contentType
* コンテントタイプ。 デフォルトはapplication/context。
* @param encoding
* エンコーディング。 指定しなかった場合は、リクエストのcharsetEncodingが設定される。
* リクエストのcharsetEncodingも指定がない場合は、UTF-8。
*/
public static void writeJSON(Object source, boolean prettyPrint, String contentType, String encoding) {
if (contentType == null) {
contentType = JSON_CONTENT_TYPE;
}
if (encoding == null) {
encoding = RequestUtil.getRequest().getCharacterEncoding();
if (encoding == null) {
encoding = JSON_ENCODING;
}
}
HttpServletResponse response = ResponseUtil.getResponse();
response.setContentType(contentType + "; charset=" + encoding);
try {
Writer out = new OutputStreamWriter(response
.getOutputStream(), encoding);
try {
JSON.encode(source, out, prettyPrint);
} finally {
out.close();
}
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
}
0 件のコメント:
コメントを投稿