Struts×JSON.simple×jQueryでJSONオブジェクトをajaxでやり取り

今更感ありありですが、これらの組み合わせでやったのは初めてだったのでメモしておきます。
やり取りするのはこんなJSONデータ。

[{"name":"太朗", "age":27}, {"name":"花子", "age":25}]

想定としては検索ボタンをクリックすると、上記データがサーバーから送られてきて以下のようにSELECTに展開するというものをやってみます。

<SELECT name="users" id="users">
  <OPTION value="0">太朗(27)</OPTION>
  <OPTION value="1">花子(25)</OPTION>
</SELECT>

クライアントサイド

まず用意しておくhtmlはこんな感じ。

<INPUT type="button" name="search_button" id="search_button" value="検索">
<SELECT name="users" id="users"></SELECT>

つづいてjavascriptはこんな感じ。

$(function(){
  $("#search_button").click(function(){
    $.getJSON(
      "http://localhost:8080/sample/user_search.do",
      function(result){
        for(var i=0; i<result.length; i++){
          $("<OPTION></OPTION>").val(i).text(resut[i].name + "(" + result[i].age + ")").appendTo("#users");
        }
      }
    );
  });
});

JSONオブジェクトをやり取りするのであれば、Ajax.getJSON関数が便利。いちいちevalしてオブジェクト化しなくても即使えます♪

サーバーサイド

JSON形式の文字列を返す際、自分で組み立ててもいいんですが既にライブラリがあるのでこれを利用します。
http://www.json.org/java/simple.txt
では、StrutsのActionクラスです。

public ActionForward execute(ActionMapping mapping,
                             ActionForm form, 
                             HttpServletRequest request, 
                             HttpServletResponse response) {
  JSONObject obj1 = new JSONObject();
  obj.put("name","太朗");
  obj.put("age",27);
  JSONObject obj2 = new JSONObject();
  obj.put("name","花子");
  obj.put("age",25);

  JSONArray json = new JSONArray();
  json.add(obj1);
  json.add(obj2);

  PrintWriter writer = response.getWriter();
  writer.print(json.toString());
  writer.close();

  return null;
}

最後をreturn null;とするところがポイントかな。