Skip to content

Instantly share code, notes, and snippets.

@hugithordarson
Created November 16, 2010 12:15
Show Gist options
  • Save hugithordarson/701748 to your computer and use it in GitHub Desktop.
Save hugithordarson/701748 to your computer and use it in GitHub Desktop.
/**
* Instantiates a java object of the given class and applies the values from the given JSONObject.
*
* @param <E> The type to create
* @param json The JSONObject to convert
* @param objectClass Class of the type to create
* @return An instance of the specified class
*/
public static <E> E objectFromJSON( JSONObject json, Class<E> objectClass ) {
try {
E object = objectClass.newInstance();
Iterator<String> i = json.keys();
while( i.hasNext() ) {
String key = i.next();
Object value = json.get( key );
Class settableClass = KVC.classForKey( objectClass, key );
if( !isAssignableFrom( settableClass, Arrays.<Class>asList( Integer.class, String.class, Boolean.class, boolean.class, int.class ) ) ) {
value = objectFromJSON( (JSONObject)value, settableClass );
}
KVC.takeValueForKey( object, key, value );
}
return object;
}
catch( Exception e ) {
System.out.println( "JSON Object creation failed" + e );
e.printStackTrace();
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment