Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jsonator
package com.mysite.model.entities;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/**
*
* @author Cecil.Meeks
*/
public abstract class Jsonator<T> implements Serializable {
private Class<T> entityClass;
private JSONObject json;
private JSONArray jsonArray;
public Jsonator(Class<T> entityClass) {
this.entityClass = entityClass;
this.json = new JSONObject();
this.jsonArray = new JSONArray();
}
public void convert(List<T> paObjectList) throws IllegalArgumentException, IllegalAccessException {
convert(paObjectList, null);
}
public void convert(List<T> paObjectList, String[] paExcludedColumns) throws IllegalArgumentException, IllegalAccessException {
try {
int count = paObjectList.size();
// convert the String array to an ArrayList. Makes it easier to find keys
List<String> excludedList = new ArrayList<String>();
if (paExcludedColumns != null) {
excludedList.addAll(Arrays.asList(paExcludedColumns));
}
for (Object obj : paObjectList) {
Class<?> kls = obj.getClass();
JSONObject objJson = new JSONObject();
Field[] fields = kls.getDeclaredFields();
for (Field field : fields) {
if (excludedList.size() > 0) {
if (!excludedList.contains(field.getName())) {
field.setAccessible(true);
objJson.put(field.getName(), field.get(obj));
}
} else {
field.setAccessible(true);
objJson.put(field.getName(), field.get(obj));
}
}
jsonArray.add(objJson);
}
json.put("count", count);
json.put("message", "Successfully found " + count + " records.");
json.put("results", jsonArray);
json.put("success", true);
}
catch (IllegalArgumentException ex) {
appendError("There was a problem. Please contact support.", "IllegalArgumentException");
}
catch (IllegalAccessException ex) {
appendError("There was a problem. Please contact support.", "IllegalAccessException");
}
catch (SecurityException ex) {
appendError("There was a problem. Please contact support.", "SecurityException");
}
catch (Exception ex) {
appendError("There was a problem. Please contact support.", "Exception");
}
}
public String results() {
return json.toJSONString();
}
private void appendError(String paMessage, String paException) {
if (!json.containsKey("success")) {
json.put("success", false);
}
if (!json.containsKey("message")) {
json.put("message", paMessage);
}
if (!json.containsKey("exception")) {
json.put("exception", paException);
}
if (!json.containsKey("results")) {
json.put("results", new JSONArray());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.