Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#registerModules()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#registerModules() . 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: BasicSerializableRepository.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public String toJSON(T t) {
    String json = "";
    if (t != null) {
        sessionFactory.getCurrentSession().refresh(t);
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModules(new JavaTimeModule());
        try {
            json = mapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            log.warn("Could not serialize to json", e);
            json = "";
        }
    }
    return json;
}
 
Example 2
Source File: ValidatedConfiguration.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
private static DivolteConfiguration mapped(final Config input) throws IOException {
    final Config resolved = input.resolve();
    final ObjectMapper mapper = new ObjectMapper();

    // snake_casing
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

    // Ignore unknown stuff in the config
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

    // Deserialization for Duration
    final SimpleModule module = new SimpleModule("Configuration Deserializers");
    module.addDeserializer(Duration.class, new DurationDeserializer());
    module.addDeserializer(Properties.class, new PropertiesDeserializer());

    mapper.registerModules(
            new Jdk8Module(),                   // JDK8 types (Optional, etc.)
            new GuavaModule(),                  // Guava types (immutable collections)
            new ParameterNamesModule(),         // Support JDK8 parameter name discovery
            module                              // Register custom deserializers module
            );

    return mapper.readValue(new HoconTreeTraversingParser(resolved.root()), DivolteConfiguration.class);
}
 
Example 3
Source File: CodegenConfigurator.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private static DynamicSettings readDynamicSettings(String configFile, Module... modules) {
    ObjectMapper mapper;

    if (FilenameUtils.isExtension(configFile.toLowerCase(Locale.ROOT), new String[]{"yml", "yaml"})) {
        mapper = Yaml.mapper().copy();
    } else {
        mapper = Json.mapper().copy();
    }

    if (modules != null && modules.length > 0) {
        mapper.registerModules(modules);
    }

    mapper.registerModule(new GuavaModule());

    try {
        return mapper.readValue(new File(configFile), DynamicSettings.class);
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage());
        throw new RuntimeException("Unable to deserialize config file: " + configFile);
    }
}
 
Example 4
Source File: SerializationUtils.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new {@link ObjectMapper} with default modules against the provided factory.
 *
 * @param mapper the instance to register default modules with
 */
public static ObjectMapper registerDefaultModules(ObjectMapper mapper) {
  // enable support for ...
  return mapper.registerModules(
      // Optional<>s
      new Jdk8Module(),
      // Protobuf objects
      new ProtobufModule());
}
 
Example 5
Source File: BootWebUtils.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public static ObjectMapper createObjectMapper(ApplicationContext applicationContext){
		ObjectMapper mapper = JsonMapper.ignoreNull().getObjectMapper();
//		h4m.disable(Hibernate4Module.Feature.FORCE_LAZY_LOADING);
		String clsName = "com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module";
		if(ClassUtils.isPresent(clsName, ClassUtils.getDefaultClassLoader())){
			Object h4m = ReflectUtils.newInstance(clsName);
			
			Class<?> featureCls = ReflectUtils.loadClass(clsName+"$Feature");
			Object field = ReflectUtils.getStaticFieldValue(featureCls, "SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS");
			ReflectUtils.invokeMethod("enable", h4m, field);

			field = ReflectUtils.getStaticFieldValue(featureCls, "FORCE_LAZY_LOADING");
			ReflectUtils.invokeMethod("disable", h4m, field);
			mapper.registerModule((Module)h4m);
		}
		List<Module> modules = SpringUtils.getBeans(applicationContext, Module.class);
		if(LangUtils.isNotEmpty(modules))
			mapper.registerModules(modules);
		return mapper;
	}
 
Example 6
Source File: ObjectMapperCustomizer.java    From moserp with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

    if (!(bean instanceof ObjectMapper)) {
        return bean;
    }

    ObjectMapper mapper = (ObjectMapper) bean;
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
    mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    registerQuantitySerializer(mapper);
    mapper.registerModules(new MoneyModule(), new JavaTimeModule(), new Jackson2HalModule());

    return mapper;
}
 
Example 7
Source File: DruidTranquilityController.java    From nifi with Apache License 2.0 6 votes vote down vote up
private List<AggregatorFactory> getAggregatorList(String aggregatorJSON) {
    ComponentLog log = getLogger();
    ObjectMapper mapper = new ObjectMapper(null);
    mapper.registerModule(new AggregatorsModule());
    mapper.registerModules(Lists.newArrayList(new SketchModule().getJacksonModules()));
    mapper.registerModules(Lists.newArrayList(new ApproximateHistogramDruidModule().getJacksonModules()));

    try {
        return mapper.readValue(
            aggregatorJSON,
            new TypeReference<List<AggregatorFactory>>() {
            }
        );
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }
}
 
Example 8
Source File: N2oEngineConfiguration.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
private ObjectMapper restObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new SimpleDateFormat(serializingFormat));
    RestEngineTimeModule module = new RestEngineTimeModule(deserializingFormats, exclusionKeys);
    objectMapper.registerModules(module);
    return objectMapper;
}
 
Example 9
Source File: BasicSerializableRepository.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public T fromJSON(String json) {
    T obj = null;
    if (StringUtils.isNotBlank(json)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModules(new JavaTimeModule());
        try {
            obj = mapper.readValue(json, getDomainClass());
        } catch (IOException e) {
            log.warn("Could not deserialize json", e);
            obj = null;
        }
    }
    return obj;
}
 
Example 10
Source File: JsonSerDeserUtils.java    From Eagle with Apache License 2.0 5 votes vote down vote up
public static <T> T deserialize(String value, Class<T> cls, List<Module> modules) throws Exception{
	ObjectMapper mapper = new ObjectMapper();
	if (modules != null) { 
		mapper.registerModules(modules);
	}
	return mapper.readValue(value, cls);	
}
 
Example 11
Source File: JsonSerDeserUtils.java    From Eagle with Apache License 2.0 5 votes vote down vote up
public static <T> String serialize(T o, List<Module> modules) throws Exception {
	ObjectMapper mapper = new ObjectMapper();
	if (modules != null) { 
		mapper.registerModules(modules);
	}
	return mapper.writeValueAsString(o);
}
 
Example 12
Source File: ReflectiveRecordSerialiser.java    From octarine with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper mapperWith(JsonSerializer<?>...extraSerialisers) {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule simpleModule = new SimpleModule("SimpleModule", Version.unknownVersion());
    simpleModule.addSerializer(new ReflectiveRecordSerialiser());
    simpleModule.addSerializer(new StreamSerialiser());
    Stream.of(extraSerialisers).forEach(simpleModule::addSerializer);

    mapper.registerModules(simpleModule);

    return mapper;
}
 
Example 13
Source File: CliModule.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Provides public ObjectMapper generalMapper() {
  /**
   * Customizes ObjectMapper for common settings.
   *
   * @param objectMapper to be customized
   * @return customized input factory
   */
  ObjectMapper objectMapper = Jackson.newObjectMapper();
  objectMapper.registerModule(new Jdk8Module());
  objectMapper.registerModules(new JavaTimeModule());
  objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  return objectMapper;
}
 
Example 14
Source File: BasicSerializableRepository.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public T fromJSON(String json) {
    T obj = null;
    if (StringUtils.isNotBlank(json)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModules(new JavaTimeModule());
        try {
            obj = mapper.readValue(json, getDomainClass());
        } catch (IOException e) {
            log.warn("Could not deserialize json", e);
            obj = null;
        }
    }
    return obj;
}
 
Example 15
Source File: MongodbDataProviderEngineTest.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
private ObjectMapper mongoObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
    RestEngineTimeModule module = new RestEngineTimeModule(new String[] {"yyyy-MM-dd'T'hh:mm:ss.SSSZ"});
    objectMapper.registerModules(module);
    return objectMapper;
}
 
Example 16
Source File: SpringRestDataProviderEngineTest.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testDateDeserializing() {
    TestRestTemplate restClient = new TestRestTemplate("{\"date_begin\":\"2018-11-17\"}");
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModules(new RestEngineTimeModule(new String[]{"yyyy-MM-dd'T'HH:mm:s", "yyyy-MM-dd"}));
    SpringRestDataProviderEngine actionEngine = new SpringRestDataProviderEngine(restClient, objectMapper);
    actionEngine.setBaseRestUrl("http://localhost:8080");
    N2oRestDataProvider dataProvider = new N2oRestDataProvider();
    dataProvider.setQuery("/test");
    Map<String, Object> request = new HashMap<>();

    DataSet result = (DataSet) actionEngine.invoke(dataProvider, request);
    assertThat(result.get("date_begin"), instanceOf(Date.class));
}
 
Example 17
Source File: RestEngineTimeModuleTest.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
private ObjectMapper createObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
    String[] patterns = {"dd.MM.yyyy HH:mm", "dd.MM.yyyy", "dd.MM.yyyy HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss"};
    String[] exclusions = {"ignore"};
    RestEngineTimeModule module = new RestEngineTimeModule(patterns, exclusions);
    objectMapper.registerModules(module);
    return objectMapper;
}
 
Example 18
Source File: JacksonUtils.java    From haven-platform with Apache License 2.0 4 votes vote down vote up
public static void registerModules(ObjectMapper objectMapper) {
    objectMapper.registerModules(new DmJacksonModule(), new Jdk8Module(), new JavaTimeModule(), new JtModule());
}
 
Example 19
Source File: RestObjectMapperFactory.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
private static void registerModules(ObjectMapper mapper) {
  // not use mapper.findAndRegisterModules()
  // because we need to sort modules, so that customers can override our default module
  List<Module> modules = SPIServiceUtils.getOrLoadSortedService(Module.class);
  mapper.registerModules(modules.toArray(new Module[modules.size()]));
}
 
Example 20
Source File: SerializableReIndexingExecutionFailuresTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
@BeforeEach
void setUp() {
    objectMapper = new ObjectMapper();
    objectMapper.registerModules(new GuavaModule());
}