自分で作ったり提供したりするものは、まず自分自身で使ってみろろということです。自分じゃ使わないものなら人はいくらでも無責任にも無思考にもなれる。そういう投げやりな「サービス」やら「プロダクツ」なんて、だれだってイヤだ。自分が作り手と同時に利用者の立場になれば、ちゃんと使えるレベルのものを提供しようとします。

2010年4月14日水曜日

GWT With JSON

この記事ではGoogle Web ToolkitのJavaコートからJavascriptのJSONオブジェクトをアクセスするサンプルを紹介します。

サンプル

ソース明細:

htmlファイル
<script type="text/javascript" language="javascript">
var jsonData = [
                { "FirstName" : "Jimmy", "LastName" : "Webber" },
                { "FirstName" : "Allan",  "LastName" : "Dayal" },
                { "FirstName" : "Keanu", "LastName" : "Spoon" },
                { "FirstName" : "Emily", "LastName" : "Rudnick" }
              ];
</script>

JSONにアクセスするため、用意したJavaクラス
public class Customer extends JavaScriptObject
{
    // Overlay types always have protected, zero-arg ctors
    protected Customer()
    {
    }

    // Typically, methods on overlay types are JSNI
    public final native String getFirstName() /*-{
        return this.FirstName;
    }-*/;

    public final native String getLastName() /*-{
        return this.LastName;
    }-*/;

    // Note, though, that methods aren't required to be JSNI
    public final String getFullName()
    {
        return getFirstName() + " " + getLastName();
    }
}

GWTアクセス関数
// Use JSNI to grab the JSON object we care about
// The JSON object gets its Java type implicitly
// based on the method's return type
private native Customer getFirstCustomer(int index) /*-{
    // Get a reference to the first customer in the JSON array from earlier
    return $wnd.jsonData[index];
}-*/;

使い方:
@Override
public void onClick(ClickEvent event)
{
    Customer c = getFirstCustomer(2);
    // Yay! Now I have a JS object that appears to be a Customer
    Window.alert("Hello, " + c.getFirstName());
}

0 件のコメント:

コメントを投稿

ホームページ