使用Gson的Java反射和递归JSON反序列化程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Gson的Java反射和递归JSON反序列化程序相关的知识,希望对你有一定的参考价值。

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.
  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. }

以上是关于使用Gson的Java反射和递归JSON反序列化程序的主要内容,如果未能解决你的问题,请参考以下文章