0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

x10でJSON文字列をパースする

Last updated at Posted at 2015-03-27

x10でJSONをパースする手法について。Managed版のx10を想定。
Javaのjsonライブラリはいくつかあるが、今回は依存ライブラリの少ないjson-simpleを使うことにした。

参考記事:

手順

json-simpleの準備

https://code.google.com/p/json-simple/downloads/list から json-simple-1.1.1.jar をダウンロード。
json-simple ライブラリでjsonのパースをするサンプルコードは以下の場所にある。
https://code.google.com/p/json-simple/wiki/DecodingExamples

x10からjson-simpleのAPIを呼ぶ

ミニマムなx10のコードは以下のとおり。

import x10.io.Console;
import x10.compiler.Native;

import x10.interop.Java;             // Javaのオブジェクトを利用するために x10.interop.Java をimport
import org.json.simple.*;            // json-simpleライブラリのクラスをimport

public class JsonTest {

  public static def main(args:Rail[String]) {
    val s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
    Console.OUT.println(s);

    val o = JSONValue.parse(s);      // 文字列をJSONとしてパース。返り値はJSONValue型。
    Console.OUT.println(o);
    val a= o as JSONArray;           // 配列にcast。JSONArray型になる。 JavaのArrayListを継承しているクラス。
    Console.OUT.println(a);

    val l = a.get(0n) as Long;       // 0番目の要素を取得。引数には `0n` と書く必要がある。0と書くとLongになり、x10のコンパイルエラーが発生。
    Console.OUT.println(l);
    Console.OUT.println(a.get(1n));
  }
}

ビルドと実行

x10コンパイル時にjarファイルをクラスパスおよびソースパスに含める必要がある。

x10c -sourcepath json-simple-1.1.1.jar -cp json-simple-1.1.1.jar JsonTest.x10
x10 -cp json-simple-1.1.1.jar JsonTest
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?