From Gentle Crane, 1 Week ago, written in Text.
This paste is a reply to Re: Untitled from Unique Water Vole - view diff
Embed
  1. Hey Guys
  2.  
  3. I've separated out the functionality of converting JavaBean to JSON in its own separate section *5.1. Serialize Java Object to JSON* (and file in git PR). There are no configurable options provided by this package (like which properties to exclude out, etc).
  4.  
  5. However, _org.json_ doesn't facilitate the reverse functionality. There's no build in method that converts a JSON to JavaBean. But I thought to include that section by providing a small Helper function that would take JSON and Class type and I came up with this:
  6.  
  7. {code}
  8. public <T> T getJavabeanFromJson(String json, Class<T> classOfT) {
  9.         JSONObject jobject = new JSONObject(json);
  10.         Object object = null;
  11.         try {
  12.                 object = classOfT.newInstance();
  13.                 for (Method method : classOfT.getMethods()) {
  14.                         if (method.getName().startsWith("set")) {
  15.                                 method.invoke(object, jobject
  16.                                   .get(Character.toLowerCase(method.getName().charAt(3)) + method.getName().substring(4)));
  17.                         }      
  18.                 }
  19.         } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
  20.                                 | InvocationTargetException e) {
  21.                 throw new JSONException(e.getMessage());
  22.         }
  23.         return classOfT.cast(object);
  24. }
  25. {code}
  26.        
  27. Although it works, but this isn't that small and conversion itself is a bit complicated. This way it feels that we're deviating from the original topic so for now, I've removed that section "5.2. Deserialize JSON to Java Object", but if you feel we can introduce this code, then please share your views, I'll add that as well.
  28.  
  29. Please refer to this updated PR: [https://github.com/eugenp/tutorials/pull/3662]
  30.  
  31. Thanks