public static Json serialize(Object obj) {
return serialize(obj, null);
}
public static Json serialize(Object obj, Field f) {
if(obj == null) return new Json(null);
Class<?> clazz = obj.getClass();
//if(obj instanceof Map<?, ?>) {
if(Map.class.isAssignableFrom(clazz)){
Map<?, ?> map = (Map<?, ?>) obj;
Json result = map();
for (Map.Entry<?, ?> entry : map.entrySet()) {
String key = entry.getKey().toString();
Json value = serialize(entry.getValue(), null);
result.put(key, value);
}
return result;
}
//if(obj instanceof Collection<?>) {
if(Collection.class.isAssignableFrom(clazz)){
Json result = list();
Collection<?> col = (Collection<?>) obj;
for (Object object : col) {
result.add(serialize(object));
}
return result;
}
if(Json.class.isAssignableFrom(clazz)){
return new Json(obj);
}
if(Field.class.isAssignableFrom(clazz)){
return new Json(obj);
}
if(clazz.isArray()){
return new Json(obj);
}
if(clazz == Class.class){
return new Json(obj);
}
if(JsonDumpable.class.isAssignableFrom(obj.getClass())) {
return ((JsonDumpable)obj).dump();
}
try {
EmbeddedList list = obj.getClass().getAnnotation(EmbeddedList.class);
if(list != null) {
return serializeList(obj);
}
EmbeddedMap map = obj.getClass().getAnnotation(EmbeddedMap.class);
if(map != null) {
return serializeMap(obj);
}
} catch(SienaException e) {
throw e;
} catch(Exception e) {
throw new SienaException(e);
}
if(f != null) {
Format format = f.getAnnotation(Format.class);
if(format != null) {
if(obj.getClass() == Date.class) {
Date date = (Date) obj;
SimpleDateFormat sdf = new SimpleDateFormat(format.value());
return new Json(sdf.format(date));
}
}
}
return new Json(obj);
}