Java Reflection and recursive JSON deserializer using Gson


/ Published in: Java
Save to your folder(s)

Change the generic class to whatever class you wish. JSON arrays, types etc, are not handled, you should do that. Purpose of this snippet is to deserialize only needed JSON keys with respect to the class members of your class.


Copy this code and paste it in your HTML
  1. import java.lang.reflect.Field;
  2. import java.lang.reflect.Type;
  3. import java.util.Iterator;
  4. import java.util.Map.Entry;
  5.  
  6. import com.google.gson.JsonDeserializationContext;
  7. import com.google.gson.JsonElement;
  8. import com.google.gson.JsonObject;
  9. import com.google.gson.JsonParseException;
  10.  
  11. public class PackagingDeserializer<PackagingResponse> implements com.google.gson.JsonDeserializer<PackagingResponse>{
  12.  
  13.  
  14. @Override
  15. public PackagingResponse deserialize(JsonElement arg0, Type arg1,
  16. JsonDeserializationContext arg2) throws JsonParseException {
  17. Class klass = ((Class)arg1);
  18. Field[] fields = klass.getDeclaredFields();
  19. PackagingResponse r = null;
  20. try {
  21. r = (PackagingResponse)klass.newInstance();
  22. } catch (InstantiationException e3) {
  23. // TODO Auto-generated catch block
  24. e3.printStackTrace();
  25. } catch (IllegalAccessException e3) {
  26. // TODO Auto-generated catch block
  27. e3.printStackTrace();
  28. }
  29. JsonObject o = arg0.getAsJsonObject();
  30. parse(o, r);
  31.  
  32. return r;
  33. }
  34.  
  35. private void parse(JsonObject o, PackagingResponse r){
  36. Iterator<Entry<String, JsonElement>> i = o.entrySet().iterator();
  37. while(i.hasNext()){
  38. Entry<String, JsonElement> e = i.next();
  39. JsonElement el = e.getValue();
  40. if(el.isJsonObject())
  41. parse(el.getAsJsonObject(), r);
  42. for(Field f : r.getClass().getDeclaredFields()){
  43. f.setAccessible(true);
  44. if(f.getName().equals(e.getKey())){
  45. try {
  46. f.set(r,el.getAsString());
  47. } catch (IllegalArgumentException e1) {
  48. // TODO Auto-generated catch block
  49. e1.printStackTrace();
  50. } catch (IllegalAccessException e1) {
  51. // TODO Auto-generated catch block
  52. e1.printStackTrace();
  53. }
  54. }
  55.  
  56. }
  57. }
  58. }
  59. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.