Revision: 64123
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at July 6, 2013 05:24 by mindinmotionmkd
Initial Code
import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.Iterator; import java.util.Map.Entry; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; public class PackagingDeserializer<PackagingResponse> implements com.google.gson.JsonDeserializer<PackagingResponse>{ @Override public PackagingResponse deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { Class klass = ((Class)arg1); Field[] fields = klass.getDeclaredFields(); PackagingResponse r = null; try { r = (PackagingResponse)klass.newInstance(); } catch (InstantiationException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } catch (IllegalAccessException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } JsonObject o = arg0.getAsJsonObject(); parse(o, r); return r; } private void parse(JsonObject o, PackagingResponse r){ Iterator<Entry<String, JsonElement>> i = o.entrySet().iterator(); while(i.hasNext()){ Entry<String, JsonElement> e = i.next(); JsonElement el = e.getValue(); if(el.isJsonObject()) parse(el.getAsJsonObject(), r); for(Field f : r.getClass().getDeclaredFields()){ f.setAccessible(true); if(f.getName().equals(e.getKey())){ try { f.set(r,el.getAsString()); } catch (IllegalArgumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } } }
Initial URL
Initial Description
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.
Initial Title
Java Reflection and recursive JSON deserializer using Gson
Initial Tags
java
Initial Language
Java