倭マン's BLOG

くだらない日々の日記書いてます。 たまにプログラミング関連の記事書いてます。 書いてます。

Maven2 プロジェクトで JSON を使う

Maven2 プロジェクトで JSON を用いるためには、プロジェクトの POM ファイルに以下のような <dependency> 要素を付加します:

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20070829</version>
</dependency>

JSON を使ったサンプル


Maven2 とはあまり関係ありませんが、『Ajax&JavaーJavaプログラマのためのAjaxプライマー』のサンプルを参考に JSON の簡単な使い方を。
JSON オブジェクト

次のような JSON オブジェクトを扱うサンプルを扱います:

{"conversion" : {
  "decimal" : "103",
  "hexadecimal" : "67",
  "octal" : "147",
  "hyper" : "&0x67",
  "binary" : "1100111B"
}}

Java コード (Server)

サーバ側で JSON オブジェクトを作成する Java コードです:

private String createJSON(int i){
    JSONObject conversion = new JSONObject();
    JSONObject data = new JSONObject();

    try{
        data.put("decimal", Integer.toString(i));
        data.put("hexadecimal", Integer.toHexString(i));
        data.put("octal", Integer.toOctalString(i));
        data.put("hyper", "&ox"+Integer.toHexString(i));
        data.put("binary", Integer.toBinaryString(i)+"B");
        
        conversion.put("conversion", data);

    }catch(JSONException ex){
        // 例外処理
    }
        
    return conversion.toString();
}

JavaScript コード (Client)

クライアント側で JSON オブジェクトからデータを取得する JavaScript コードです:

var req;    // XMLHttpRequest or ActiveXObject

function populate(){
  var jsonData = req.responseText;
  var data = eval('('+jsonData+')');
  
  var decimal = document.getElementById('decimal');
  decimal.value = data.conversion.decimal;
  
  var hex = document.getElementById('hexadecimal');
  hex.value = data.conversion.hexadecimal;
  
  var octal = document.getElementById('octal');
  octal.value = data.conversion.octal;
  
  var hyper = document.getElementById('hyper');
  hyper.value = data.conversion.hyper;
  
  var binary = document.getElementById('bin');
  binary.value = data.conversion.binary;
}