Search in sources :

Example 1 with AttributeConverter

use of hse.holuhoev.ruz.converter.AttributeConverter in project hse-cws by holuhoev.

the class JsonParser method parse.

public <T> List<T> parse(String str, Class<T> clazz) {
    if (str == null)
        return null;
    JsonArray jsonArray = new JsonArray(str);
    List<T> list = new LinkedList<>();
    try {
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonObject jsonObject = jsonArray.getJsonObject(i);
            T object = clazz.newInstance();
            for (Field field : clazz.getDeclaredFields()) {
                JsonAttribute jsonAttributeAnnotation = field.getAnnotation(JsonAttribute.class);
                if (jsonAttributeAnnotation != null) {
                    field.setAccessible(true);
                    Object value = jsonObject.getMap().get(isNullOrEmpty(jsonAttributeAnnotation.name()) ? field.getName() : jsonAttributeAnnotation.name());
                    if (field.getAnnotation(Convert.class) != null) {
                        Object converterInstance = field.getAnnotation(Convert.class).converter().newInstance();
                        if (converterInstance instanceof AttributeConverter) {
                            value = ((AttributeConverter) converterInstance).convertToEntityAttribute(value);
                        }
                    }
                    field.set(object, value);
                }
            }
            list.add(object);
        }
        return list;
    } catch (InstantiationException | IllegalAccessException e) {
        logger.error(e.getMessage());
    }
    return null;
}
Also used : Convert(hse.holuhoev.ruz.converter.Convert) JsonObject(io.vertx.core.json.JsonObject) LinkedList(java.util.LinkedList) JsonArray(io.vertx.core.json.JsonArray) Field(java.lang.reflect.Field) AttributeConverter(hse.holuhoev.ruz.converter.AttributeConverter) JsonObject(io.vertx.core.json.JsonObject)

Aggregations

AttributeConverter (hse.holuhoev.ruz.converter.AttributeConverter)1 Convert (hse.holuhoev.ruz.converter.Convert)1 JsonArray (io.vertx.core.json.JsonArray)1 JsonObject (io.vertx.core.json.JsonObject)1 Field (java.lang.reflect.Field)1 LinkedList (java.util.LinkedList)1