I basically am making webrequests and recieving a JSON response. Depending on the request, I am parsing JSON request into objects I have created. The parsing is pretty much the same no matter what the object Im parsing into looks like. So I have a bunch of methods doing the same work only with different objects, I was wondering how I could accomplish this with generics? Here is an example
public static ArrayList<Contact> parseStuff(String responseData) {
ArrayList<Person> People = new ArrayList<Person>();
try {
JSONArray jsonPeople = new JSONArray(responseData);
if (!jsonPeople.isNull(0)) {
for (int i = 0; i < jsonPeople.length(); i++) {
People.add(new Person(jsonPeople.getJSONObject(i)));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
}
return People;
}
You should look at Effective Java 2, Item 29: Consider typesafe heterogeneous type containers
The basic idea is that you could imagine you have some
Deserializerinterface. Then you can have aMap<Class<?>, Deserializer<String, Object>>. The map is basically a registry from type to the properDeserializerfor that type (which deserializes from a String (perhaps you want a json type or something instead of String, but String works) to the type of interest.The real trick is that you must enforce that the class key type matches the deserializer type. i.e. – For some Class that is a key in the map, you have a Deserializer as a value. You can do this with a generic method. For example:
Then to use the heterogeneous map, you can use a generic method again:
You use the type that is specified by the method caller to
I hope what I said was at least somewhat clear. Reading the corresponding entry in EJ2 should help!
UPDATE:
As Abhinav points out, the GSON library will help you accomplish your final goal of deserializing objects in a way that uses generics appropriately. However, I think your question is more about generics than the end goal so I feel my answer is more appropriate. GSON must be implemented using a heterogeneous type container :-).
Thanks, Abhinav for pointing out GSON!