use of com.serotonin.json.spi.JsonEntity in project ma-core-public by infiniteautomation.
the class JsonContext method getConverter.
/**
* Returns the class converter for the given class.
*
* @param clazz
* the class to look up
* @return the converter that is bound to the class. May be null if no converter was registered.
* @throws JsonException
*/
public ClassConverter getConverter(Class<?> clazz) throws JsonException {
// First check if the class is already in the map.
ClassConverter converter = classConverters.get(clazz);
if (converter != null)
return converter;
// Check for inheritance
Class<?> sc = clazz.getSuperclass();
while (sc != null && sc != Object.class) {
converter = classConverters.get(sc);
if (converter != null) {
classConverters.put(clazz, converter);
return converter;
}
sc = sc.getSuperclass();
}
// Check for enum
if (Enum.class.isAssignableFrom(clazz)) {
converter = classConverters.get(Enum.class);
if (converter != null) {
classConverters.put(clazz, converter);
return converter;
}
}
// Check for map
if (Map.class.isAssignableFrom(clazz)) {
converter = classConverters.get(Map.class);
if (converter != null) {
classConverters.put(clazz, converter);
return converter;
}
}
// Check for collection
if (Collection.class.isAssignableFrom(clazz)) {
converter = classConverters.get(Collection.class);
if (converter != null) {
classConverters.put(clazz, converter);
return converter;
}
}
// Check for array
if (clazz.isArray()) {
converter = classConverters.get(Array.class);
if (converter != null) {
classConverters.put(clazz, converter);
return converter;
}
}
//
// Introspect the class.
boolean jsonSerializable = JsonSerializable.class.isAssignableFrom(clazz);
boolean jsonEntity = clazz.isAnnotationPresent(JsonEntity.class);
List<SerializableProperty> properties = new ArrayList<>();
BeanInfo info;
try {
info = Introspector.getBeanInfo(clazz);
} catch (IntrospectionException e) {
throw new JsonException(e);
}
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
// Annotations or beans
Class<?> currentClazz = clazz;
while (currentClazz != Object.class) {
boolean annotationsFound = addAnnotatedProperties(currentClazz, descriptors, properties);
if (!annotationsFound && !currentClazz.isAnnotationPresent(JsonEntity.class) && !jsonSerializable)
// Not annotated and no property annotations were found. Consider it a POJO.
addPojoProperties(currentClazz, descriptors, properties);
currentClazz = currentClazz.getSuperclass();
}
if (properties.isEmpty())
properties = null;
// Create a converter?
if (jsonSerializable || jsonEntity || properties != null) {
converter = new JsonPropertyConverter(jsonSerializable, properties);
classConverters.put(clazz, converter);
return converter;
}
// Give up
throw new JsonException("No converter for class " + clazz);
}
Aggregations