ksaitoの日記

日々試したことの覚え書き

json-simple

移転しました。

自動的にリダイレクトします。

JSONは、JavaScriptで使われる軽量のデータフォーマットで、仕様は、RFC 4627で標準化されています。
google codeのjson-simpleというAPIJavaオブジェクトとJSONフォーマットを相互変換することができます。

サンプル

簡単なサンプルです。
JavaオブジェクトをJSON文字列に変換/逆変換します。

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class JsonSample {
    public JsonSample() {
    }

    public String createJsonString() {
        JSONObject json = new JSONObject();
        json.put("name", "object name");
        json.put("Integer", new Integer(10));
        json.put("Double", new Double(10.5));
        json.put("Boolean", new Boolean(true));
        json.put("Null", null);

        return json.toString();
    }

    public static void main(String[] args) {
        JsonSample json = new JsonSample();
        System.out.println(json.createJsonString());

        Object jsonobj = JSONValue.parse(json.createJsonString());
        System.out.println("jsonobj=" + jsonobj.toString());
    }
}

JavaオブジェクトからJSON文字列の作成

JSONObjectクラスのインスタンスJavaオブジェクトをputしてtoStringメソッドJSON文字列を取得します。

JSON文字列からJavaオブジェクトの作成

JSONValueクラスのparseメソッドを使ってJSON文字列をパースしObjectクラスを作成します。