use of com.openmeap.json.Enum in project OpenMEAP by OpenMEAP.
the class JSONObjectBuilder method toJSON.
public JSONObject toJSON(Object obj) throws JSONException {
if (obj == null) {
return null;
}
if (!HasJSONProperties.class.isAssignableFrom(obj.getClass())) {
throw new RuntimeException("The rootObject being converted to JSON must implement the HasJSONProperties interface.");
}
JSONProperty[] properties = ((HasJSONProperties) obj).getJSONProperties();
JSONObject jsonObj = new JSONObject();
// iterate over each JSONProperty annotated method
for (int jsonPropertyIdx = 0; jsonPropertyIdx < properties.length; jsonPropertyIdx++) {
JSONProperty property = properties[jsonPropertyIdx];
// determine the method return type
Class returnType = property.getReturnType();
Object value = property.getGetterSetter().getValue(obj);
if (value == null) {
continue;
}
if (returnType == null) {
throw new JSONException(obj.getClass().getName() + "." + property.getPropertyName() + " is annotated with JSONProperty, but has no return type." + " I can't work with this.");
}
// strip "get" off the front
String propertyName = property.getPropertyName();
try {
if (Enum.class.isAssignableFrom(returnType)) {
Enum ret = (Enum) value;
jsonObj.put(propertyName, ret.value());
} else if (isSimpleType(returnType)) {
jsonObj.put(propertyName, handleSimpleType(returnType, property.getGetterSetter().getValue(obj)));
} else {
if (returnType.isArray()) {
Object[] returnValues = (Object[]) value;
JSONArray jsonArray = new JSONArray();
for (int returnValueIdx = 0; returnValueIdx < returnValues.length; returnValueIdx++) {
Object thisValue = returnValues[returnValueIdx];
jsonArray.put(toJSON(thisValue));
}
jsonObj.put(propertyName, jsonArray);
} else if (Hashtable.class.isAssignableFrom(returnType)) {
Hashtable map = (Hashtable) value;
JSONObject jsonMap = new JSONObject();
Enumeration enumer = map.keys();
while (enumer.hasMoreElements()) {
Object key = (String) enumer.nextElement();
Object thisValue = (Object) map.get(key);
if (isSimpleType(thisValue.getClass())) {
jsonMap.put(key.toString(), handleSimpleType(returnType, thisValue));
} else {
jsonMap.put(key.toString(), toJSON(thisValue));
}
}
jsonObj.put(propertyName, jsonMap);
} else if (Vector.class.isAssignableFrom(returnType)) {
Vector returnValues = (Vector) property.getGetterSetter().getValue(obj);
JSONArray jsonArray = new JSONArray();
int size = returnValues.size();
for (int returnValueIdx = 0; returnValueIdx < size; returnValueIdx++) {
Object thisValue = returnValues.elementAt(returnValueIdx);
if (isSimpleType(property.getContainedType())) {
jsonArray.put(thisValue);
} else {
jsonArray.put(toJSON(thisValue));
}
}
jsonObj.put(propertyName, jsonArray);
} else {
jsonObj.put(propertyName, toJSON(value));
}
}
} catch (Exception ite) {
throw new JSONException(ite);
}
}
return jsonObj;
}
Aggregations