軽量なJSONシリアライザ Jsonizer 0.9.2 をリリースしました。Java6上で動作します。あらかじめテンプレートを定義しておき、オブジェクトに対してテンプレートを再帰的に適用してシリアライズするのが特徴です。
以前は Object.getClass() に厳密に合致するテンプレートのみ適用していました。さすがに使いにくいので、 instanceof テストを行って利用可能なテンプレートを検索するようにしました。インタフェースに対するテンプレートを登録できるようになりました。
一風変わったシリアライザですが、お使いいただけると幸いです。
// Slim3のモデルをシリアライズする例 public class DataController extends Controller { public Navigation run() throws Exception { Jsonizer jsonizer = new Jsonizer(); // モデルHogeに対するテンプレートを定義します。 jsonizer.type(Hoge.class).with(new PropertyGetter<Hoge>() { private final HogeMeta m = HogeMeta.get(); public void get(Hoge e) { // オブジェクトとJSONのプロパティ対応を書きます。 property(Datastore.keyToString(e.getKey())).as(m.key); property(e.getUrl()).as(m.url); property(e.getDate().getTime()).as(m.date); } }); // 対象 List<Hoge> hoges = hogeService.getAll(); // シリアライズしてJSONをレスポンスします。 jsonizer.jsonize(hoges).send(response); return null; } }
Algorithm
An object O is given, apply recursively:
- if O is null, primitive, boxed or collection:
- apply literal transformation
- if O.getClass() returns class C and found exactly matched PropertyGetter
: - apply get() method in PropertyGetter
- apply get() method in PropertyGetter
- perform instanceof test lookup:
- for each class C in registered PropertyGetter
- if O instanceof C:
- apply get() method in PropertyGetter
- apply get() method in PropertyGetter
- if O instanceof C:
- Note that instanceof test order is undefined (not sorted by inheritance tree depth).
- for each class C in registered PropertyGetter
- otherwise:
- O.toString()
自分の英語力に絶望した><