/*
* Created on Jun 21, 2008
*/
package com.skaringa.javaxml.example;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import com.skaringa.javaxml.DeserializerException;
import com.skaringa.javaxml.NoImplementationException;
import com.skaringa.javaxml.ObjectTransformer;
import com.skaringa.javaxml.ObjectTransformerFactory;
import com.skaringa.javaxml.SerializerException;
/**
* Demonstrate the usage of the JSON serializer and deserializer.
*/
public class JsonExample {
/**
* MAIN.
* @param args Program arguments (not used).
*/
public static void main(String[] args) {
// Construct a Person.
Person fred = new Person(101, "Fred", "Feuerstein", "ff@email.com");
try {
// Get an ObjectTransformer.
// The ObjectTransformer interface offers all needed methods.
ObjectTransformer trans = ObjectTransformerFactory.getInstance()
.getImplementation();
// Serialize the Person object into a file.
FileOutputStream out = new FileOutputStream("fred.js");
trans.serializeToJson(fred, out);
out.close();
// Read a Person's JSON file and create a new Person object
// from its content.
FileInputStream in = new FileInputStream("fred.js");
Person freddy = (Person) trans.deserializeFromJson(in, Person.class);
in.close();
// Check the result.
if (fred.equals(freddy)) {
System.out.println("OK");
} else {
System.out.println("ERROR");
}
// now deserialize the JSON file into a map instead of a person
in = new FileInputStream("fred.js");
Map fredMap = (Map) trans.deserializeFromJson(in);
in.close();
System.out.println(fredMap);
} catch (NoImplementationException e) {
System.err.println(e);
} catch (SerializerException e) {
System.err.println(e);
} catch (DeserializerException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
}