Friday, May 7, 2010

Convert POJO to JSON

Face this issue many times.


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class POJO2JSON {

public static JSONArray convert(Class cls, List list) {

Method[] methods = cls.getDeclaredMethods();

String className = cls.getSimpleName();
className = className.substring(0,1).toLowerCase() + className.substring(1);

JSONArray jsonarray = new JSONArray();
for (Object object : list) {
JSONObject json = new JSONObject();

for (Method method : methods) {
if(method.getName().startsWith("get")) {
String fieldName = method.getName().substring(3);
fieldName = fieldName.substring(0,1).toLowerCase() + fieldName.substring(1);

try {
Object result = method.invoke(object, null);
// System.out.println(fieldName + " = " + result);
json.put(fieldName, result);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
jsonarray.put(json);
}
return jsonarray;
}

public static JSONObject convert(Class cls, Object obj) {


Method[] methods = cls.getDeclaredMethods();

String className = cls.getSimpleName();
className = className.substring(0,1).toLowerCase() + className.substring(1);

JSONObject json_class = new JSONObject();

JSONObject json = new JSONObject();

for (Method method : methods) {
if(method.getName().startsWith("get")) {
String fieldName = method.getName().substring(3);
fieldName = fieldName.substring(0,1).toLowerCase() + fieldName.substring(1);

try {
Object result = method.invoke(obj, null);
// System.out.println(fieldName + " = " + result);
json.put(fieldName, result);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
try {
json_class.put(className, json);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
}

See http://www.json.org/java/ for JSONObject