com.fasterxml.jackson.databind.deser.BeanDeserializerModifier Java Examples

The following examples show how to use com.fasterxml.jackson.databind.deser.BeanDeserializerModifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ObjectMapperFactory.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
private static ObjectMapper configureObjectMapper(
        ObjectMapper objectMapper, boolean shouldIncludeRawResponses) {
    if (shouldIncludeRawResponses) {
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config,
                                                          BeanDescription beanDesc,
                                                          JsonDeserializer<?> deserializer) {
                if (Response.class.isAssignableFrom(beanDesc.getBeanClass())) {
                    return new RawResponseDeserializer(deserializer);
                }

                return deserializer;
            }
        });

        objectMapper.registerModule(module);
    }

    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return objectMapper;
}
 
Example #2
Source File: ObjectMapperFactory.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static ObjectMapper configureObjectMapper(
        ObjectMapper objectMapper, boolean shouldIncludeRawResponses) {
    if (shouldIncludeRawResponses) {
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config,
                                                          BeanDescription beanDesc,
                                                          JsonDeserializer<?> deserializer) {
                if (Response.class.isAssignableFrom(beanDesc.getBeanClass())) {
                    return new RawResponseDeserializer(deserializer);
                }

                return deserializer;
            }
        });

        objectMapper.registerModule(module);
    }

    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return objectMapper;
}
 
Example #3
Source File: StandaloneConfiguration.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new GraviteeMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
                                                             final JavaType type,
                                                             BeanDescription beanDesc,
                                                             final JsonDeserializer<?> deserializer) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                    Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                }
            };
        }
    });

    mapper.registerModule(module);

    return mapper;
}
 
Example #4
Source File: GenerateBatch.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
static SimpleModule getCustomDeserializationModel(final File includesDir) {
    // Create a module which loads our config files, but supports a special "!include" key which can point to an existing config file.
    // This allows us to create a sort of meta-config which holds configs which are otherwise required at CLI time (via generate task).
    // That is, this allows us to create a wrapper config for generatorName, inputSpec, outputDir, etc.
    SimpleModule module = new SimpleModule("GenerateBatch");
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config,
                                                      BeanDescription bd, JsonDeserializer<?> original) {
            JsonDeserializer<?> result;
            if (bd.getBeanClass() == DynamicSettings.class) {
                result = new DynamicSettingsRefSupport(original, includesDir);
            } else {
                result = original;
            }
            return result;
        }
    });

    return module;
}
 
Example #5
Source File: FlatteningDeserializer.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default deserializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
            if (BeanDeserializer.class.isAssignableFrom(deserializer.getClass())) {
                // Apply flattening deserializer on all POJO types.
                return new FlatteningDeserializer(beanDesc.getBeanClass(), deserializer, mapper);
            } else {
                return deserializer;
            }
        }
    });
    return module;
}
 
Example #6
Source File: AdditionalPropertiesDeserializer.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default deserializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
            for (Class<?> c : TypeToken.of(beanDesc.getBeanClass()).getTypes().classes().rawTypes()) {
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    if ("additionalProperties".equalsIgnoreCase(field.getName())) {
                        JsonProperty property = field.getAnnotation(JsonProperty.class);
                        if (property != null && property.value().isEmpty()) {
                            return new AdditionalPropertiesDeserializer(beanDesc.getBeanClass(), deserializer, mapper);
                        }
                    }
                }
            }
            return deserializer;
        }
    });
    return module;
}
 
Example #7
Source File: AdditionalPropertiesDeserializer.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default deserializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
            for (Class<?> c : TypeToken.of(beanDesc.getBeanClass()).getTypes().classes().rawTypes()) {
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    if ("additionalProperties".equalsIgnoreCase(field.getName())) {
                        JsonProperty property = field.getAnnotation(JsonProperty.class);
                        if (property != null && property.value().isEmpty()) {
                            return new AdditionalPropertiesDeserializer(beanDesc.getBeanClass(), deserializer, mapper);
                        }
                    }
                }
            }
            return deserializer;
        }
    });
    return module;
}
 
Example #8
Source File: ObjectMapperFactory.java    From vividus with Apache License 2.0 6 votes vote down vote up
public static ObjectMapper createWithCaseInsensitiveEnumDeserializer()
{
    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier()
    {
        @Override
        public JsonDeserializer<Enum<?>> modifyEnumDeserializer(DeserializationConfig config, final JavaType type,
                BeanDescription beanDescription, final JsonDeserializer<?> deserializer)
        {
            return new JsonDeserializer<>()
            {
                @SuppressWarnings({ "unchecked", "rawtypes" })
                @Override
                public Enum<?> deserialize(JsonParser parser, DeserializationContext context) throws IOException
                {
                    return Enum.valueOf((Class<? extends Enum>) type.getRawClass(),
                            parser.getValueAsString().toUpperCase());
                }
            };
        }
    });
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(module);
    return objectMapper;
}
 
Example #9
Source File: FlatteningDeserializer.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default deserializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
            if (BeanDeserializer.class.isAssignableFrom(deserializer.getClass())) {
                // Apply flattening deserializer on all POJO types.
                return new FlatteningDeserializer(beanDesc.getBeanClass(), deserializer, mapper);
            } else {
                return deserializer;
            }
        }
    });
    return module;
}
 
Example #10
Source File: XmlParserModule.java    From allure2 with Apache License 2.0 6 votes vote down vote up
@Override
public void setupModule(final SetupContext context) {
    super.setupModule(context);
    context.addBeanDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyCollectionDeserializer(final DeserializationConfig config,
                                                                final CollectionType type,
                                                                final BeanDescription beanDesc,
                                                                final JsonDeserializer<?> deserializer) {
            if (deserializer instanceof CollectionDeserializer) {
                return new ListDeserializer((CollectionDeserializer) deserializer);
            } else {
                return super.modifyCollectionDeserializer(config, type, beanDesc,
                        deserializer);
            }
        }
    });
}
 
Example #11
Source File: ObjectMapperFactory.java    From web3j with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper configureObjectMapper(
        ObjectMapper objectMapper, boolean shouldIncludeRawResponses) {
    if (shouldIncludeRawResponses) {
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(
                new BeanDeserializerModifier() {
                    @Override
                    public JsonDeserializer<?> modifyDeserializer(
                            DeserializationConfig config,
                            BeanDescription beanDesc,
                            JsonDeserializer<?> deserializer) {
                        if (Response.class.isAssignableFrom(beanDesc.getBeanClass())) {
                            return new RawResponseDeserializer(deserializer);
                        }

                        return deserializer;
                    }
                });

        objectMapper.registerModule(module);
    }

    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return objectMapper;
}
 
Example #12
Source File: AWSUtil.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Set all prefixed properties on {@link ClientConfiguration}.
 * @param config
 * @param configProps
 */
public static void setAwsClientConfigProperties(ClientConfiguration config,
												Properties configProps) {

	Map<String, Object> awsConfigProperties = new HashMap<>();
	for (Map.Entry<Object, Object> entry : configProps.entrySet()) {
		String key = (String) entry.getKey();
		if (key.startsWith(AWS_CLIENT_CONFIG_PREFIX)) {
			awsConfigProperties.put(key.substring(AWS_CLIENT_CONFIG_PREFIX.length()), entry.getValue());
		}
	}
	// Jackson does not like the following properties
	String[] ignorableProperties = {"secureRandom"};
	BeanDeserializerModifier modifier = new BeanDeserializerModifierForIgnorables(
		ClientConfiguration.class, ignorableProperties);
	DeserializerFactory factory = BeanDeserializerFactory.instance.withDeserializerModifier(
		modifier);
	ObjectMapper mapper = new ObjectMapper(null, null,
		new DefaultDeserializationContext.Impl(factory));

	JsonNode propTree = mapper.convertValue(awsConfigProperties, JsonNode.class);
	try {
		mapper.readerForUpdating(config).readValue(propTree);
	} catch (IOException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example #13
Source File: AbstractMetricsDispatcher.java    From gradle-metrics-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Register Jackson module that maps enums as lowercase. Per http://stackoverflow.com/a/24173645.
 */
@SuppressWarnings("rawtypes")
private static void registerEnumModule(ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
                                                             final JavaType type,
                                                             BeanDescription beanDesc,
                                                             final JsonDeserializer<?> deserializer) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                    @SuppressWarnings("unchecked") Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                }
            };
        }
    });
    module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
        @Override
        public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(value.name().toLowerCase());
        }
    });
    mapper.registerModule(module);
}
 
Example #14
Source File: ObjectMapperResolver.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
public ObjectMapperResolver() {
    mapper = new GraviteeMapper();

    //because Permissions are represented as char[]
    mapper.enable(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS);

    // register filter provider
    registerFilterProvider();

    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
                                                             final JavaType type,
                                                             BeanDescription beanDesc,
                                                             final JsonDeserializer<?> deserializer) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                    Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                }
            };
        }
    });
    module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
        @Override
        public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(value.name().toLowerCase());
        }
    });
    mapper.registerModule(module);
    
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
 
Example #15
Source File: ObjectMapperResolver.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
public ObjectMapperResolver() {
    mapper = new GraviteeMapper();

    //because Permissions are represented as char[]
    mapper.enable(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS);

    // register filter provider
    registerFilterProvider();

    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
                                                             final JavaType type,
                                                             BeanDescription beanDesc,
                                                             final JsonDeserializer<?> deserializer) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                    Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                }
            };
        }
    });
    module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
        @Override
        public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(value.name().toLowerCase());
        }
    });
    mapper.registerModule(module);
}
 
Example #16
Source File: JacksonUtils.java    From JglTF with MIT License 5 votes vote down vote up
/**
 * Creates a BeanDeserializerModifier that replaces the 
 * SettableBeanProperties in the BeanDeserializerBuilder with
 * ErrorReportingSettableBeanProperty instances that forward
 * information about errors when setting bean properties to the
 * given consumer. (Don't ask ... )  
 * 
 * @param jsonErrorConsumer The consumer for {@link JsonError}s.
 * If this is <code>null</code>, then no errors will be reported.
 * @return The modifier
 */
private static BeanDeserializerModifier 
    createErrorHandlingBeanDeserializerModifier(
        Consumer<? super JsonError> jsonErrorConsumer)
{
    return new BeanDeserializerModifier()
    {
        @Override
        public BeanDeserializerBuilder updateBuilder(
            DeserializationConfig config,
            BeanDescription beanDesc,
            BeanDeserializerBuilder builder)
        {
            Iterator<SettableBeanProperty> propertiesIterator =
                builder.getProperties();
            while (propertiesIterator.hasNext())
            {
                SettableBeanProperty property = propertiesIterator.next();
                SettableBeanProperty wrappedProperty =
                    new ErrorReportingSettableBeanProperty(
                        property, jsonErrorConsumer);
                builder.addOrReplaceProperty(wrappedProperty, true);
            }
            return builder;
        }
    };    
}
 
Example #17
Source File: ObjectMapperFactory.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper configureObjectMapper(
        ObjectMapper objectMapper, boolean shouldIncludeRawResponses) {
    if (shouldIncludeRawResponses) {
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(
                new BeanDeserializerModifier() {
                    @Override
                    public JsonDeserializer<?> modifyDeserializer(
                            DeserializationConfig config,
                            BeanDescription beanDesc,
                            JsonDeserializer<?> deserializer) {
                        if (Response.class.isAssignableFrom(beanDesc.getBeanClass())) {
                            return new RawResponseDeserializer(deserializer);
                        }

                        return deserializer;
                    }
                });

        objectMapper.registerModule(module);
    }

    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return objectMapper;
}
 
Example #18
Source File: RestEngineTimeModule.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
public RestEngineTimeModule(String[] patterns, String[] exclusionKeys) {
    this();
    setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
            if (beanDesc.getBeanClass() == String.class) {
                CustomDateDeserializer dateDeserializer = new CustomDateDeserializer(deserializer);
                dateDeserializer.setPatterns(patterns);
                dateDeserializer.setExclusions(exclusionKeys);
                return dateDeserializer;
            }
            return deserializer;
        }
    });
}
 
Example #19
Source File: RestEngineTimeModule.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
public RestEngineTimeModule(String[] patterns) {
    this();
    setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
            if (beanDesc.getBeanClass() == String.class) {
                CustomDateDeserializer dateDeserializer = new CustomDateDeserializer(deserializer);
                dateDeserializer.setPatterns(patterns);
                return dateDeserializer;
            }
            return deserializer;
        }
    });
}
 
Example #20
Source File: AWSUtil.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Set all prefixed properties on {@link ClientConfiguration}.
 * @param config
 * @param configProps
 */
public static void setAwsClientConfigProperties(ClientConfiguration config,
												Properties configProps) {

	Map<String, Object> awsConfigProperties = new HashMap<>();
	for (Map.Entry<Object, Object> entry : configProps.entrySet()) {
		String key = (String) entry.getKey();
		if (key.startsWith(AWS_CLIENT_CONFIG_PREFIX)) {
			awsConfigProperties.put(key.substring(AWS_CLIENT_CONFIG_PREFIX.length()), entry.getValue());
		}
	}
	// Jackson does not like the following properties
	String[] ignorableProperties = {"secureRandom"};
	BeanDeserializerModifier modifier = new BeanDeserializerModifierForIgnorables(
		ClientConfiguration.class, ignorableProperties);
	DeserializerFactory factory = BeanDeserializerFactory.instance.withDeserializerModifier(
		modifier);
	ObjectMapper mapper = new ObjectMapper(null, null,
		new DefaultDeserializationContext.Impl(factory));

	JsonNode propTree = mapper.convertValue(awsConfigProperties, JsonNode.class);
	try {
		mapper.readerForUpdating(config).readValue(propTree);
	} catch (IOException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example #21
Source File: AWSUtil.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Set all prefixed properties on {@link ClientConfiguration}.
 * @param config
 * @param configProps
 */
public static void setAwsClientConfigProperties(ClientConfiguration config,
												Properties configProps) {

	Map<String, Object> awsConfigProperties = new HashMap<>();
	for (Map.Entry<Object, Object> entry : configProps.entrySet()) {
		String key = (String) entry.getKey();
		if (key.startsWith(AWS_CLIENT_CONFIG_PREFIX)) {
			awsConfigProperties.put(key.substring(AWS_CLIENT_CONFIG_PREFIX.length()), entry.getValue());
		}
	}
	// Jackson does not like the following properties
	String[] ignorableProperties = {"secureRandom"};
	BeanDeserializerModifier modifier = new BeanDeserializerModifierForIgnorables(
		ClientConfiguration.class, ignorableProperties);
	DeserializerFactory factory = BeanDeserializerFactory.instance.withDeserializerModifier(
		modifier);
	ObjectMapper mapper = new ObjectMapper(null, null,
		new DefaultDeserializationContext.Impl(factory));

	JsonNode propTree = mapper.convertValue(awsConfigProperties, JsonNode.class);
	try {
		mapper.readerForUpdating(config).readValue(propTree);
	} catch (IOException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example #22
Source File: ObjectMapperResolver.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
public ObjectMapperResolver() {
    mapper = new ObjectMapper();

    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
                                                             final JavaType type,
                                                             BeanDescription beanDesc,
                                                             final JsonDeserializer<?> deserializer) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                    Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                }
            };
        }
    });
    module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
        @Override
        public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(value.name().toLowerCase());
        }
    });
    module.addSerializer(Instant.class, new StdSerializer<Instant>(Instant.class) {
        @Override
        public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeNumber(instant.toEpochMilli());
        }
    });
    module.addDeserializer(JWK.class, new StdDeserializer<JWK>(JWK.class) {
        @Override
        public JWK deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            JsonNode node = jsonParser.getCodec().readTree(jsonParser);
            String kty = node.get("kty").asText();
            if (kty == null) {
                return null;
            }
            JWK jwk = null;
            switch (kty) {
                case "RSA":
                    jwk = jsonParser.getCodec().treeToValue(node, RSAKey.class);
                    break;
                case "EC":
                    jwk = jsonParser.getCodec().treeToValue(node, ECKey.class);
                    break;
                case "oct":
                    jwk = jsonParser.getCodec().treeToValue(node, OCTKey.class);
                    break;
                case "OKP":
                    jwk = jsonParser.getCodec().treeToValue(node, OKPKey.class);
                    break;
            }
            return jwk;
        }
    });
    mapper.addMixIn(Domain.class, MixIn.class);
    mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.registerModule(module);
    mapper.registerModule(new Jdk8Module());
    mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
}
 
Example #23
Source File: DeserializerModule.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
public DeserializerModule(BeanDeserializerModifier deserializerModifier) {
    super("DeserializerModule", Version.unknownVersion());
    this.deserializerModifier = deserializerModifier;
}
 
Example #24
Source File: SimpleModule.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @since 2.2
 */
public SimpleModule setDeserializerModifier(BeanDeserializerModifier mod) {
    _deserializerModifier = mod;
    return this;
}
 
Example #25
Source File: BeanConfigFactoryManager.java    From logsniffer with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@PostConstruct
private void initJsonMapper() {
	final SimpleModule module = new SimpleModule();
	module.setDeserializerModifier(new BeanDeserializerModifier() {
		@Override
		public JsonDeserializer<?> modifyDeserializer(final DeserializationConfig config,
				final BeanDescription beanDesc, final JsonDeserializer<?> deserializer) {
			if (ConfiguredBean.class.isAssignableFrom(beanDesc.getBeanClass())) {
				return new ConfiguredBeanDeserializer(deserializer);
			}
			return deserializer;
		}
	});
	jsonMapper.registerModule(module);
	if (postConstructors != null) {
		for (final BeanPostConstructor<?> bpc : postConstructors) {
			mappedPostConstrucors.put(bpc.getClass(), bpc);
		}
	}

	// Register sub beans
	final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
			false);
	final AssignableTypeFilter filter4configBenas = new AssignableTypeFilter(ConfiguredBean.class);
	scanner.addIncludeFilter(filter4configBenas);

	for (final BeanDefinition bd : scanner.findCandidateComponents("com.logsniffer")) {
		try {
			final Class<? extends ConfiguredBean> clazz = (Class<? extends ConfiguredBean>) Class
					.forName(bd.getBeanClassName());
			final JsonTypeName jsonNameAnnotation = clazz.getAnnotation(JsonTypeName.class);
			final List<String> names = new ArrayList<String>();
			configBeanNames.put(clazz, names);
			if (jsonNameAnnotation != null) {
				names.add(jsonNameAnnotation.value());
				if (jsonNameAnnotation.deprecated() != null) {
					for (final String dep : jsonNameAnnotation.deprecated()) {
						names.add(dep);
					}
				}
			}
			names.add(clazz.getSimpleName());
			logger.debug("Registered JSON type {} for following names: {}", clazz, names);
		} catch (final ClassNotFoundException e) {
			logger.warn("Failed to register JSON type name for " + bd.getBeanClassName(), e);
		}
	}
}
 
Example #26
Source File: Module.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Method that module can use to register additional modifier objects to
 * customize configuration and construction of bean deserializers.
 * 
 * @param mod Modifier to register
 */
public void addBeanDeserializerModifier(BeanDeserializerModifier mod);