views:

66

answers:

3

I'm trying to write a data access layer for an AJAX web project. This DAL has to convert data coming in via an AJAX servlet to objects that can be passed to a PreparedStatement for execution.

Data in the AJAX servlet, retrieved by using HttpServletRequest.getParameter(...), come in as strings.

In each data class, I have a known set of fields as well as their data types, e.g. CustomerId(integer), CustomerName(string).

I can of course write a method in the Customer class to handle the conversion, but this means I have to do it for every data object's class. I would much rather have a generic method that does conversion, e.g.

Object convert(String value, Class<?> targetType) { ... }

Can anyone point me in the right direction?

A: 

There are JSON libraries that will do data type conversion. Jackson is one. Or, you could code the whole think using a JAX-RS service framework instead of a raw servlet, and it will take care of all this for you. Apache CXF is one framework that contains this support. Since you are asking for a generic solution, why not use one that's already out there.

bmargulies
A: 

We do this exact thing using a plethora of static converters in a utility class. It isn't elegant but it sure is easy and effective.

class Util {
    public static Long StringToLong(String s) { ... }
    public static Integer StringToInt(String s) { ... }
    public static Date StringToDate(String s) { ... }
    public static Date StringToDateYYMMDD(String s) { ... }
    public static BigDecimal StringToBigDecimal(String s) { ... }
    // etc ad naseum
}
Tony Ennis
+1  A: 

Create an utility class with all conversion methods you would like to use. Inside its static initializer, make use of reflection to collect all those methods by parameter type and return type in a map. Then, in the convert() method just pick the method which suits the given source and target type and invoke it. Make use of generics to fix the return type to be the same as the target type:

public static <T> T convert(Object from, Class<T> to) 

You can find an example in this article.


But as bmargulies pointed out, JSON is also an interesting option. You could let ajax to send all parameters as one JSON string. Then, you can use a JSON-to-Javabean converter like Google Gson to convert the JSON string to a fullworthy Javabean like Customer. It'll be as simple as:

String jsondata = request.getParameter("jsondata");
Customer customer = new Gson().fromJson(jsondata, Customer.class);
// ...

See also this answer for another example.

BalusC