Search in sources :

Example 36 with BeanDescription

use of com.fasterxml.jackson.databind.BeanDescription in project tutorials by eugenp.

the class JacksonDynamicIgnoreUnitTest method setUp.

@Before
public void setUp() {
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.registerModule(new SimpleModule() {

        @Override
        public void setupModule(final SetupContext context) {
            super.setupModule(context);
            context.addBeanSerializerModifier(new BeanSerializerModifier() {

                @Override
                public JsonSerializer<?> modifySerializer(final SerializationConfig config, final BeanDescription beanDesc, final JsonSerializer<?> serializer) {
                    if (Hidable.class.isAssignableFrom(beanDesc.getBeanClass())) {
                        return new HidableSerializer((JsonSerializer<Object>) serializer);
                    }
                    return serializer;
                }
            });
        }
    });
}
Also used : HidableSerializer(com.baeldung.jackson.dynamicIgnore.HidableSerializer) SerializationConfig(com.fasterxml.jackson.databind.SerializationConfig) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) JsonSerializer(com.fasterxml.jackson.databind.JsonSerializer) SimpleModule(com.fasterxml.jackson.databind.module.SimpleModule) BeanSerializerModifier(com.fasterxml.jackson.databind.ser.BeanSerializerModifier) Before(org.junit.Before)

Example 37 with BeanDescription

use of com.fasterxml.jackson.databind.BeanDescription in project Gaffer by gchq.

the class JsonSerialisationUtil method getSerialisedFieldClasses.

/**
 * Gets all the fields and their classes for a given class.
 *
 * @param className the class name to find the fields for.
 * @return a map of field name to class name
 */
public static Map<String, String> getSerialisedFieldClasses(final String className) {
    final Map<String, String> cachedResult = cache.get(className);
    if (null != cachedResult) {
        return cachedResult;
    }
    final Class<?> clazz;
    try {
        clazz = Class.forName(SimpleClassNameIdResolver.getClassName(className));
    } catch (final Exception e) {
        throw new IllegalArgumentException("Class name was not recognised: " + className, e);
    }
    final ObjectMapper mapper = new ObjectMapper();
    final JavaType type = mapper.getTypeFactory().constructType(clazz);
    final BeanDescription introspection = mapper.getSerializationConfig().introspect(type);
    final Class<?> builder = introspection.findPOJOBuilder();
    String buildMethodPrefix = "with";
    if (null != builder) {
        JsonPOJOBuilder anno = findAnnotation(builder, JsonPOJOBuilder.class);
        if (null != anno) {
            buildMethodPrefix = anno.withPrefix();
        }
    }
    Constructor<?> creator = null;
    for (final Constructor<?> constructor : type.getRawClass().getDeclaredConstructors()) {
        final JsonCreator anno = constructor.getAnnotation(JsonCreator.class);
        if (null != anno) {
            creator = constructor;
            break;
        }
    }
    final List<BeanPropertyDefinition> properties = introspection.findProperties();
    final Map<String, String> fieldMap = new HashMap<>();
    for (final BeanPropertyDefinition property : properties) {
        final String propName = property.getName();
        final String propClass;
        if ("class".equals(propName)) {
            propClass = Class.class.getName();
        } else {
            Type genericType = null;
            if (null != builder) {
                final String methodName = buildMethodPrefix + propName;
                Method matchedMethod = null;
                for (final Method method : builder.getMethods()) {
                    if (methodName.equalsIgnoreCase(method.getName())) {
                        final Type[] params = method.getGenericParameterTypes();
                        if (null != params && 1 == params.length) {
                            final JsonSetter jsonSetter = method.getAnnotation(JsonSetter.class);
                            if (null != jsonSetter && propName.equals(jsonSetter.value())) {
                                matchedMethod = method;
                                break;
                            }
                            final JsonProperty jsonProperty = method.getAnnotation(JsonProperty.class);
                            if (null != jsonProperty && propName.equals(jsonProperty.value())) {
                                matchedMethod = method;
                                break;
                            }
                            if (null == matchedMethod) {
                                matchedMethod = method;
                            } else if (builder.equals(method.getReturnType())) {
                                // Checks for overridden methods
                                matchedMethod = method;
                            }
                        }
                    }
                }
                if (null != matchedMethod) {
                    genericType = matchedMethod.getGenericParameterTypes()[0];
                }
            }
            if (null == genericType && null != creator) {
                for (final Parameter parameter : creator.getParameters()) {
                    final JsonProperty anno = parameter.getAnnotation(JsonProperty.class);
                    if (null != anno && propName.equals(anno.value())) {
                        if (null != parameter.getParameterizedType()) {
                            genericType = parameter.getParameterizedType();
                        } else {
                            genericType = parameter.getType();
                        }
                        break;
                    }
                }
            }
            if (null == genericType && null != property.getSetter() && null != property.getSetter().getGenericParameterTypes() && 1 == property.getSetter().getGenericParameterTypes().length) {
                genericType = property.getSetter().getGenericParameterTypes()[0];
            }
            if (null != genericType && genericType instanceof Class && ((Class) genericType).isEnum()) {
                genericType = String.class;
            }
            if (null == genericType) {
                propClass = Object.class.getName();
            } else {
                propClass = getFieldTypeString(clazz, genericType);
            }
        }
        fieldMap.put(propName, propClass);
    }
    final Map<String, Map<String, String>> newCache = new HashMap<>(cache);
    newCache.put(className, Collections.unmodifiableMap(fieldMap));
    cache = Collections.unmodifiableMap(newCache);
    return fieldMap;
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) HashMap(java.util.HashMap) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) JsonCreator(com.fasterxml.jackson.annotation.JsonCreator) Method(java.lang.reflect.Method) JavaType(com.fasterxml.jackson.databind.JavaType) Type(java.lang.reflect.Type) JavaType(com.fasterxml.jackson.databind.JavaType) JsonSetter(com.fasterxml.jackson.annotation.JsonSetter) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) JsonPOJOBuilder(com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder) Parameter(java.lang.reflect.Parameter) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 38 with BeanDescription

use of com.fasterxml.jackson.databind.BeanDescription in project Gaffer by gchq.

the class GraphConfigurationServiceV2 method getSerialisedFields.

@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Need to wrap all runtime exceptions before they are given to the user")
@Override
public Response getSerialisedFields(final String className) {
    final Class<?> clazz;
    try {
        clazz = Class.forName(SimpleClassNameIdResolver.getClassName(className));
    } catch (final Exception e) {
        throw new IllegalArgumentException("Class name was not recognised: " + className, e);
    }
    final ObjectMapper mapper = new ObjectMapper();
    final JavaType type = mapper.getTypeFactory().constructType(clazz);
    final BeanDescription introspection = mapper.getSerializationConfig().introspect(type);
    final List<BeanPropertyDefinition> properties = introspection.findProperties();
    final Set<String> fields = new HashSet<>();
    for (final BeanPropertyDefinition property : properties) {
        fields.add(property.getName());
    }
    return Response.ok(fields).header(GAFFER_MEDIA_TYPE_HEADER, GAFFER_MEDIA_TYPE).build();
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 39 with BeanDescription

use of com.fasterxml.jackson.databind.BeanDescription in project Gaffer by gchq.

the class GraphConfigurationService method getSerialisedFields.

@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Need to wrap all runtime exceptions before they are given to the user")
@Override
public Set<String> getSerialisedFields(final String className) {
    final Class<?> clazz;
    try {
        clazz = Class.forName(SimpleClassNameIdResolver.getClassName(className));
    } catch (final Exception e) {
        throw new IllegalArgumentException("Class name was not recognised: " + className, e);
    }
    final ObjectMapper mapper = new ObjectMapper();
    final JavaType type = mapper.getTypeFactory().constructType(clazz);
    final BeanDescription introspection = mapper.getSerializationConfig().introspect(type);
    final List<BeanPropertyDefinition> properties = introspection.findProperties();
    final Set<String> fields = new HashSet<>();
    for (final BeanPropertyDefinition property : properties) {
        fields.add(property.getName());
    }
    return fields;
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 40 with BeanDescription

use of com.fasterxml.jackson.databind.BeanDescription in project java-chassis by ServiceComb.

the class TestLambdaMetafactoryUtils method should_support_primitive_type.

@Test
public void should_support_primitive_type() {
    Child child = new Child();
    ObjectMapper mapper = JsonUtils.OBJ_MAPPER;
    BeanDescription beanDescription = mapper.getSerializationConfig().introspect(mapper.constructType(Child.class));
    List<BeanPropertyDefinition> properties = beanDescription.findProperties();
    assertThat(properties).hasSize(2);
    for (int idx = 0; idx < properties.size(); idx++) {
        BeanPropertyDefinition property = properties.get(idx);
        Setter<Object, Object> setter = createObjectSetter(property.getSetter().getAnnotated());
        setter.set(child, idx);
        Getter<Object, Object> getter = createObjectGetter(property.getGetter().getAnnotated());
        Object value = getter.get(child);
        assertThat(value).isEqualTo(idx);
    }
}
Also used : BeanDescription(com.fasterxml.jackson.databind.BeanDescription) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Aggregations

BeanDescription (com.fasterxml.jackson.databind.BeanDescription)47 JavaType (com.fasterxml.jackson.databind.JavaType)25 BeanPropertyDefinition (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition)24 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)13 SimpleModule (com.fasterxml.jackson.databind.module.SimpleModule)12 ArrayList (java.util.ArrayList)10 Annotation (java.lang.annotation.Annotation)9 DeserializationConfig (com.fasterxml.jackson.databind.DeserializationConfig)8 NamedType (com.fasterxml.jackson.databind.jsontype.NamedType)8 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)7 HashSet (java.util.HashSet)7 SerializationConfig (com.fasterxml.jackson.databind.SerializationConfig)6 AnnotatedMethod (com.fasterxml.jackson.databind.introspect.AnnotatedMethod)6 Type (java.lang.reflect.Type)6 LinkedHashMap (java.util.LinkedHashMap)6 JsonDeserializer (com.fasterxml.jackson.databind.JsonDeserializer)5 BeanDeserializerModifier (com.fasterxml.jackson.databind.deser.BeanDeserializerModifier)5 JsonSerializer (com.fasterxml.jackson.databind.JsonSerializer)4 BeanSerializerModifier (com.fasterxml.jackson.databind.ser.BeanSerializerModifier)4 JsonIgnoreProperties (com.fasterxml.jackson.annotation.JsonIgnoreProperties)3