/ Published in: Java
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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); PackagingResponse r = null; try { r = (PackagingResponse)klass.newInstance(); // TODO Auto-generated catch block e3.printStackTrace(); // TODO Auto-generated catch block e3.printStackTrace(); } JsonObject o = arg0.getAsJsonObject(); parse(o, r); return r; } private void parse(JsonObject o, PackagingResponse r){ while(i.hasNext()){ JsonElement el = e.getValue(); if(el.isJsonObject()) parse(el.getAsJsonObject(), r); f.setAccessible(true); if(f.getName().equals(e.getKey())){ try { f.set(r,el.getAsString()); // TODO Auto-generated catch block e1.printStackTrace(); // TODO Auto-generated catch block e1.printStackTrace(); } } } } } }