Created
November 16, 2010 12:15
-
-
Save hugithordarson/701748 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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