I am trying to create a utility class that accepts any type of POJO, and converts that POJO into a JSON object. It should use Java reflections and annotations to look through certain getter methods and create a key, value JSON element based on that.
I am trying to use generics to do this, but it doesn’t seem to work. Is this not possible?
I want to pass a class object as a parameter and retrieve the correct class methods if possible.
Code I have written so far:
package com.jr.freedom.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import net.sf.json.JSONObject;
public class JsonParserUtil {
private static final String GET_CHAR_SEQUENCE = "get";
public static <T> JSONObject toJsonObject(Class<T> classObject) {
// get Method names with @JsonElement included
Method methods[] = classObject.class.getDeclaredMethods();
JSONObject jsonObject = new JSONObject();
try {
for (int i = 0; i < methods.length; i++) {
String key = methods[i].getName();
System.out.println(key);
if (methods[i].isAnnotationPresent(JsonElement.class) && key.contains(GET_CHAR_SEQUENCE)) {
key.replaceFirst(GET_CHAR_SEQUENCE, "");
jsonObject.put(key, methods[i].invoke(classObject));
}
}
return jsonObject;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Here is the testMethod that tries to use the above JSON util object
User user = new User();
user.setBio("bio mate");
user.setCountry("uk");
user.setEmailAddress("jonney@ooglemail.com");
user.setFirstName("jono");
user.setPassword("passwordfdsadsa");
user.setUsername("crazy8");
JSONObject jsonUser = new JsonParserUtil<User>().toJsonObject(user);
User class is a simple POJO with getters and setters. Currently this line: Method methods[] = T.class.getDeclaredMethods(); won’t work, as you can’t use the generic T to get the DeclaredMethods. Is there a way to do so? Or do I have to create this util method for every single POJO I make?
I know it will work using: Method methods[] = User.class.getDeclaredMethods(); but that will only be applicable for the User class. I am trying to create a util JSON class that can take any POJO object and try to create a JSONObject automatically.
Solution:
The key being to use