Google-gson is a java library from Google for encoding and decoding JSON text.
Get the latest binaries from
http://code.google.com/p/google-gson/.
The following example shows registering a custom serializer for a specific type.
/**
* @param args
*/ public static void main(String[] args) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Password.class, new PasswordSerializer()) //Register a custom
.setPrettyPrinting().create(); //serializer for Password type.
Student3 stud = new Student3("Sriram", "Kasireddi", 2, "Singing", new Date(110, 4, 6));
stud.setPassword(new Password("abcdefg"));
System.out.println(gson.toJson(stud));
}
}
class PasswordSerializer implements JsonSerializer<Password> {
@Override public JsonElement serialize(Password src, Type typeOfSrc, JsonSerializationContext context) {
//Encrypt password using some Encryption algorithm...
//For now this serializer reverses the password string return new JsonPrimitive(new StringBuffer(src.getPassword()).reverse().toString());
}
}