YAJT
About
Tutorial
Links
Sourceforge
Event Handling and Serialization
Data la complessa struttura che può raggiungere un oggetto nel formalismo JSON, si è pensato di ricorrere a qualche artifizio per
la visita e la serializzazione.
Il design pattern Visitor è proprio quello che fa al caso nostro: nel package di base è definita una interfaccia JSONHandler
che rappresenta il visitor ed intercetterà gli eventi prodotti dalla visita degli oggetti JSON.
Supponiamo ad esempio implementare un enumeratore di tutte le chiavi di un oggetto JSON:
public final class DummyHandler implements JSONHandler { public void element(Object value) throws JSONException {} public void endArray() throws JSONException {} public void endDocument() throws JSONException {} public void endObject() throws JSONException {} public void separeElement() throws JSONException {} public void startArray() throws JSONException {} public void startDocument() throws JSONException {} public void startElement(String key) throws JSONException { System.out.println("Found key: " + key); } public void startObject() throws JSONException {} public void visit(AbstractJSONObject jsonObject) throws JSONException {} }A questo punto, data una variabile di referenza ad un oggetto JSON, che immaginiamo essere lo stesso come descritto in The JSON query path, basta fargli accettare il visitor:
JSONObject obj = ... obj.acceptVisitor(new DummyHandler());Man mano che verrà effettuata la visita, l'Handler produrrà il seguente output:
Found key: keyA Found key: keyB Found key: test Found key: test2 Found key: keyC Found key: keyDUna volta afferrato questo concetto, è altrettanto facile capire come viene effettuata la serializzazione degli oggetti JSON: nel package
net.sourceforge.yajt.impl
è cotenuta una implementazione di un particolare JSONHandler:
JSONHandler serializer = JSONFactory.newSerializer(System.out); serializer.startDocument(); obj.acceptVisitor(serializer); serializer.endDocument();Il serializzatore viene costruito a partire dello stream di output sul quale andrà a serializzare tutti gli eventi JSON, lo si fa accettare come visitor all'oggetto JSON e questo verrà serializzato nell'
OutputStream
di destinazione.A questo punto è anche facile pensare come il serializzatore sia riusabile per poter convertire in un flusso di output anche oggetti non JSON: essendo nota l'interfaccia, basta far "scatenare" determinati eventi in fase di trasformazione, ma questo spetta alla vostra più disparata fantasia ;)