Back to project page Android-Lib-Database.
The source code is released under:
Apache License
If you think the Android project Android-Lib-Database listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package android.lib.database; //from w w w . java 2 s . co m import java.lang.reflect.Field; import java.util.Iterator; import org.json.JSONException; import org.json.JSONObject; /** * Maps a {@link android.database.Cursor} or a {@link org.json.JSONObject} object to an instance of <code>T</code>. * @param <T> the type of instance to map. */ public class JSONRowMapper<T> extends RowMapper<T> { /** * Creates a new instance of {@link RowMapper} with the given class type. * @param clazz the class of the type to map. */ public JSONRowMapper(final Class<T> clazz) { super(clazz); } /** * Maps a {@link org.json.JSONObject} object to an instance of <code>T</code>. * @param json the {@link org.json.JSONObject} object to map. * @return an instance of <code>T</code>. * @throws JSONException if no such mapping exists. * @throws IllegalAccessException if the if the default constructor of <code>T</code> is not visible, * or the default constructor of the {@link TypeConverter} associated with any field of <code>T</code> is not visible. * @throws InstantiationException if the instance of <code>T</code> can not be created, * or the instance of the {@link TypeConverter} associated with any field of <code>T</code> can not be created. * @throws IllegalArgumentException if the column name is not found from the given <code>cursor</code>. */ public final T mapRow(final JSONObject json) throws IllegalArgumentException, IllegalAccessException, InstantiationException, JSONException { final T t = this.clazz.newInstance(); for (final Iterator<String> key = json.keys(); key.hasNext();) { final String name = key.next(); Field field = null; try { field = this.clazz.getDeclaredField(name); } catch (final SecurityException e) { } catch (final NoSuchFieldException e) { } if (field == null) { try { field = this.clazz.getField(name); } catch (final SecurityException e) { } catch (final NoSuchFieldException e) { } } if (field != null) { field.setAccessible(true); field.set(this, json.get(name)); } } return t; } }