How do I correctly use generics?
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开发者_Python百科 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 Deserializer
interface. Then you can have a Map<Class<?>, Deserializer<String, Object>>
. The map is basically a registry from type to the proper Deserializer
for 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:
<T> void put(Class<T> clazz, Deserializer<String, T> deserializer) {
map.put(clazz, deserializer);
}
Then to use the heterogeneous map, you can use a generic method again:
<T> T deserialize(Class<T> typeToDeserializeFromJson, String toDeserialize) {
return typeToDeserializeFromJson.cast(
deserializers.get(tTDFJ).deserialize(toDeserialize));
}
You use the type that is specified by the method caller to
- lookup the right `Deserializer`
- deserialize the json text to an `Object`
- safely cast the `Object` to the right type which we know is safe because of how we constructed the map in the first place.
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!
I would suggest you use GSON instead of JSON. It really simplifies your life.
精彩评论