use of org.eclipse.scout.rt.platform.annotations.IgnoreProperty in project scout.rt by eclipse.
the class JsonBean method toJson.
@Override
public Object toJson() {
if (m_bean == null) {
return null;
}
Class<?> type = m_bean.getClass();
// basic types
if (type.isPrimitive() || type == String.class || type == Boolean.class || Number.class.isAssignableFrom(type)) {
return m_bean;
}
// binary resource
if (BinaryResource.class.isAssignableFrom(type)) {
BinaryResource binaryResource = (BinaryResource) m_bean;
m_binaryResourceMediator.addBinaryResource(binaryResource);
return m_binaryResourceMediator.createUrl(binaryResource);
}
// array
if (type.isArray()) {
JSONArray jsonArray = new JSONArray();
int n = Array.getLength(m_bean);
for (int i = 0; i < n; i++) {
IJsonObject jsonObject = createJsonObject(Array.get(m_bean, i));
jsonArray.put(jsonObject.toJson());
}
return jsonArray;
}
// collection
if (Collection.class.isAssignableFrom(type)) {
JSONArray jsonArray = new JSONArray();
Collection collection = (Collection) m_bean;
for (Object object : collection) {
IJsonObject jsonObject = createJsonObject(object);
jsonArray.put(jsonObject.toJson());
}
return jsonArray;
}
// Map
if (Map.class.isAssignableFrom(type)) {
JSONObject jsonMap = new JSONObject();
Map map = (Map) m_bean;
@SuppressWarnings("unchecked") Set<Entry> entries = (Set<Entry>) map.entrySet();
for (Entry entry : entries) {
if (!(entry.getKey() instanceof String)) {
throw new IllegalArgumentException("Cannot convert " + type + " to json object");
}
IJsonObject jsonObject = createJsonObject(entry.getValue());
jsonMap.put((String) entry.getKey(), jsonObject.toJson());
}
return jsonMap;
}
// bean
if (type.getName().startsWith("java.")) {
throw new IllegalArgumentException("Cannot convert " + type + " to json object");
}
try {
TreeMap<String, Object> properties = new TreeMap<>();
for (Field f : type.getFields()) {
if (Modifier.isStatic(f.getModifiers())) {
continue;
}
String key = f.getName();
Object val = f.get(m_bean);
IJsonObject jsonObject = createJsonObject(val);
properties.put(key, jsonObject.toJson());
}
FastBeanInfo beanInfo = new FastBeanInfo(type, Object.class);
for (FastPropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
Method m = desc.getReadMethod();
if (m == null) {
continue;
}
// skip ignored annotated getters with context GUI
IgnoreProperty ignoredPropertyAnnotation = m.getAnnotation(IgnoreProperty.class);
if (ignoredPropertyAnnotation != null && Context.GUI.equals(ignoredPropertyAnnotation.value())) {
continue;
}
String key = desc.getName();
Object val = m.invoke(m_bean);
IJsonObject jsonObject = createJsonObject(val);
properties.put(key, jsonObject.toJson());
}
JSONObject jbean = new JSONObject();
for (Map.Entry<String, Object> e : properties.entrySet()) {
jbean.put(e.getKey(), e.getValue());
}
return jbean;
} catch (Exception e) {
throw new IllegalArgumentException(type + " to json", e);
}
}
Aggregations