# Templated JSON parsing methods that work with an element or elements array

Consider the following two Java methods. The first takes a JSON string representing one element, the second representing multiple elements. gson.fromJson() can be called with a Class parameter or a Class[] parameter. The trick is in unifying the method signatures so a caller of creatBean() can call seamlessly with a Class or Class[] parameter. Is there a way these two can be combined?

public <T extends ValidateableBean>T createBean(String json, Class<T> clazz) {
Gson gson = new Gson();
T device = gson.fromJson(json, clazz);

InputValidation inputValidation = new InputValidation();
if (!inputValidation.validate((ValidateableBean) device, "Error during validation")) {
}

return device;
}

public <T extends ValidateableBean>T[] createBeans(String json, Class<T[]> clazz) {
Gson gson = new Gson();
T[] devices = gson.fromJson(json, clazz);

InputValidation inputValidation = new InputValidation();
for (T device : devices) {
if (!inputValidation.validate((ValidateableBean) device, "Error during validation")) {

• Seeing your question for the first time, I took Class<T[]> clazz to be an error and Class<T>[] clazz to be intended - foolishly, I think revisiting this. I can't see varargs helping here - it just gives a slightly more pleasing syntax for zero to many "homogeneous" arguments specified individually. There's more to creating beans for one or several elements than call seamlessly: you get a variable number of results, too. – greybeard Feb 15 at 20:55