Last active
January 15, 2016 17:33
-
-
Save rickyngk/52d7d2b1ece87f445970 to your computer and use it in GitHub Desktop.
Entity X import JSON
This file contains 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
public void importFromJson(JSONObject input) throws Exception{ | |
for (Field field : this.getClass().getDeclaredFields()) { | |
String fieldName = field.getName(); | |
if (fields.containsKey(fieldName)) { | |
field.setAccessible(true); | |
EntityMetaData t = fields.get(fieldName); | |
if (input.has(t.key)) { | |
if (t.isArray) { | |
JSONArray array = null; | |
try { | |
array = input.getJSONArray(t.key); | |
} catch (Exception E) { | |
array = null; | |
} | |
if (array != null) { | |
List list = (List) castList(t.collectionType); | |
if (t.isDerivedFromEntity) { | |
for (int i = 0; i < array.length(); i++) { | |
list.add(castObject(array.getJSONObject(i), t.entityType)); | |
} | |
} else { | |
for (int i = 0; i < array.length(); i++) { | |
Object data = array.get(i); | |
list.add(data); | |
} | |
} | |
field.set(this, list); | |
} | |
} else { | |
if (t.isDerivedFromEntity) { | |
field.set(this, castObject(input.getJSONObject(t.key), t.entityType)); | |
} else { | |
Object data = input.get(t.key); | |
field.set(this, data); | |
} | |
} | |
} | |
} | |
} | |
} | |
private <T extends EntityX> T castObject(JSONObject obj, Class<T> type) throws Exception { | |
if (obj != null) { | |
T w = type.newInstance(); | |
w.importFromJson(obj); | |
return w; | |
} else { | |
return null; | |
} | |
} | |
private <T> T castList(Class<T> type) throws Exception { | |
T w = type.newInstance(); | |
return w; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment