From Unique Water Vole, 8 Months ago, written in Text.
This paste is a reply to Untitled from Cobalt Bison - view diff
  1. Hey Guys
  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).
  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:
  7.         public <T> T getJavabeanFromJson(String json, Class<T> classOfT) {
  8.                 JSONObject jobject = new JSONObject(json);
  9.                 Object object = null;
  10.                 try {
  11.                         object = classOfT.newInstance();
  12.                         for (Method method : classOfT.getMethods()) {
  13.                                 if (method.getName().startsWith("set")) {
  14.                                         method.invoke(object, jobject
  15.                                           .get(Character.toLowerCase(method.getName().charAt(3)) + method.getName().substring(4)));
  16.                                 }      
  17.                         }
  18.                 } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
  19.                                 | InvocationTargetException e) {
  20.                         throw new JSONException(e.getMessage());
  21.                 }
  22.                 return classOfT.cast(object);
  23.         }
  25. 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.
  27. Please refer to this updated PR:
  29. Thanks

Replies to Re: Untitled rss

Title Name Language When
Re: Re: Untitled Gentle Crane text 8 Months ago.