com.fasterxml.jackson.databind.Module Java Examples

The following examples show how to use com.fasterxml.jackson.databind.Module. 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 Project: onetwo   Author: wayshall   File: BootWebUtils.java    License: 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 #2
Source Project: graphql-spqr   Author: leangen   File: JacksonValueMapperFactory.java    License: Apache License 2.0 6 votes vote down vote up
private Module getDeserializersModule(GlobalEnvironment environment, ObjectMapper mapper) {
    return new Module() {
        @Override
        public String getModuleName() {
            return "graphql-spqr-deserializers";
        }

        @Override
        public Version version() {
            return Version.unknownVersion();
        }

        @Override
        public void setupModule(SetupContext setupContext) {
            setupContext.addDeserializers(new ConvertingDeserializers(environment, mapper));
        }
    };
}
 
Example #3
Source Project: endpoints-java   Author: cloudendpoints   File: ConfiguredObjectMapper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds a {@link ConfiguredObjectMapper} using the configuration specified in this builder.
 *
 * @return the constructed object
 */
public ConfiguredObjectMapper build() {
  CacheKey key = new CacheKey(config, modules.build());
  ConfiguredObjectMapper instance = cache.get(key);
  if (instance == null) {
    ObjectMapper mapper =
        ObjectMapperUtil.createStandardObjectMapper(key.apiSerializationConfig);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS);
    for (Module module : key.modulesSet) {
      mapper.registerModule(module);
    }
    instance = new ConfiguredObjectMapper(mapper);

    // Evict all entries if the cache grows beyond a certain size.
    if (maxCacheSize <= cache.size()) {
      cache.clear();
    }

    cache.put(key, instance);
    logger.atFine().log("Cache miss, created ObjectMapper");
  } else {
    logger.atFine().log("Cache hit, reusing ObjectMapper");
  }
  return instance;
}
 
Example #4
Source Project: Eagle   Author: eBay   File: JsonSerDeserUtils.java    License: 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 #5
Source Project: eagle   Author: apache   File: KafkaConsumerOffsetFetcher.java    License: Apache License 2.0 5 votes vote down vote up
public KafkaConsumerOffsetFetcher(ZKConfig config, String... parameters) {
    try {
        this.curator = CuratorFrameworkFactory.newClient(config.zkQuorum, config.zkSessionTimeoutMs, 15000,
            new RetryNTimes(config.zkRetryTimes, config.zkRetryInterval));
        curator.start();
        this.zkRoot = config.zkRoot;
        mapper = new ObjectMapper();
        Module module = new SimpleModule("offset").registerSubtypes(new NamedType(KafkaConsumerOffset.class));
        mapper.registerModule(module);
        zkPathToPartition = String.format(config.zkRoot, parameters);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source Project: heroic   Author: spotify   File: FilterRegistry.java    License: Apache License 2.0 5 votes vote down vote up
public Module module(final QueryParser parser) {
    final SimpleModule m = new SimpleModule("filter");

    for (final Map.Entry<Class<? extends Filter>, JsonSerializer<Filter>> e : this
        .serializers.entrySet()) {
        m.addSerializer(e.getKey(), e.getValue());
    }

    final FilterJsonDeserializer deserializer =
        new FilterJsonDeserializer(ImmutableMap.copyOf(deserializers), typeNameMapping, parser);
    m.addDeserializer(Filter.class, deserializer);
    return m;
}
 
Example #7
Source Project: minnal   Author: minnal   File: DefaultJsonSerializerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterMultipleModules() {
	ObjectMapper mapper = spy(new ObjectMapper());
	serializer = new DefaultJsonSerializer(mapper) {
		@Override
		protected void registerModules(ObjectMapper mapper) {
			mapper.registerModule(new SimpleModule());
			mapper.registerModule(new SimpleModule());
			mapper.registerModule(new SimpleModule());
		}
	};
	verify(mapper, times(3)).registerModule(any(Module.class));
}
 
Example #8
Source Project: jackson-modules-base   Author: FasterXML   File: ObjectMapperModule.java    License: Apache License 2.0 5 votes vote down vote up
public ObjectMapperProvider(List<Key<? extends Module>> modulesToInject,
    List<Module> modulesToAdd, ObjectMapper mapper)
{
  this.modulesToInject = modulesToInject;
  this.modulesToAdd = modulesToAdd;
  objectMapper = mapper;
  this.providedModules = new ArrayList<Provider<? extends Module>>();
}
 
Example #9
Source Project: Eagle   Author: eBay   File: JsonSerDeserUtils.java    License: 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 #10
Source Project: immutables   Author: immutables   File: JacksonCodecs.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create module from existing registry
 */
private static Module module(final CodecRegistry registry) {
  Objects.requireNonNull(registry, "registry");
  return new Module() {
    @Override
    public String getModuleName() {
      return JacksonCodecs.class.getSimpleName();
    }

    @Override
    public Version version() {
      return Version.unknownVersion();
    }

    @Override
    public void setupModule(SetupContext context) {
      context.addSerializers(serializers(registry));
      context.addDeserializers(deserializers(registry));
    }

    @Override
    public Object getTypeId() {
      // return null so multiple modules can be registered
      // with same ObjectMapper instance
      return null;
    }
  };
}
 
Example #11
Source Project: ob1k   Author: outbrain   File: JsonRequestMarshaller.java    License: Apache License 2.0 5 votes vote down vote up
public JsonRequestMarshaller(Module... module) {
  factory = new JsonFactory();
  mapper = new ObjectMapper(factory);
  mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  for (Module m : module) {
    mapper.registerModule(m);
  }
  marshallingStrategy = new JacksonMarshallingStrategy(mapper);
}
 
Example #12
Source Project: camunda-bpm-reactor   Author: camunda   File: JsonCodec.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@code JsonCodec} that will create instances of {@code inputType}  when
 * decoding. The {@code customModule} will be registered with the underlying {@link
 * ObjectMapper}.
 *
 * @param inputType    The type to create when decoding.
 * @param customModule The module to register with the underlying ObjectMapper
 * @param delimiter    A nullable delimiting byte for batch decoding
 */
@SuppressWarnings("unchecked")
public JsonCodec(Class<IN> inputType, Module customModule, Byte delimiter) {
  super(delimiter);
  requireNonNull(inputType, "inputType must not be null");
  this.inputType = inputType;

  this.mapper = new ObjectMapper();
  if (null != customModule) {
    this.mapper.registerModule(customModule);
  }
}
 
Example #13
Source Project: carbon-apimgt   Author: wso2   File: ObjectMapperFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static ObjectMapper create(JsonFactory jsonFactory, boolean includePathDeserializer,
        boolean includeResponseDeserializer) {
    ObjectMapper mapper = jsonFactory == null ? new ObjectMapper() : new ObjectMapper(jsonFactory);

    Module deserializerModule = new DeserializationModule(includePathDeserializer, includeResponseDeserializer);
    mapper.registerModule(deserializerModule);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return mapper;
}
 
Example #14
Source Project: james-project   Author: apache   File: JsonExtractor.java    License: Apache License 2.0 5 votes vote down vote up
public JsonExtractor(Class<RequestT> type, List<Module> modules) {
    this.objectMapper = new ObjectMapper()
        .registerModule(new Jdk8Module())
        .registerModule(new GuavaModule())
        .registerModules(modules);
    this.type = type;
}
 
Example #15
Source Project: graphql-spqr   Author: leangen   File: JacksonValueMapperFactory.java    License: Apache License 2.0 5 votes vote down vote up
private Module getAnnotationIntrospectorModule(Map<Class, Class> unambiguousTypes, Map<Type, List<NamedType>> ambiguousTypes, MessageBundle messageBundle) {
    SimpleModule module = new SimpleModule("graphql-spqr-annotation-introspector") {
        @Override
        public void setupModule(SetupContext context) {
            super.setupModule(context);
            context.insertAnnotationIntrospector(new AnnotationIntrospector(ambiguousTypes, messageBundle));
        }
    };
    unambiguousTypes.forEach(module::addAbstractTypeMapping);
    return module;
}
 
Example #16
Source Project: endpoints-java   Author: cloudendpoints   File: ConfiguredObjectMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildWithModules_manyWithEmpty() {
  ConfiguredObjectMapper result1 =
      builder.addRegisteredModules(ImmutableList.<Module>of()).build();
  assertEquals(1, cache.size());
  ConfiguredObjectMapper result2 =
      builder.addRegisteredModules(ImmutableList.<Module>of()).build();
  assertEquals(1, cache.size());
  assertSame(result1, result2);
}
 
Example #17
Source Project: james-project   Author: apache   File: JsonTransformer.java    License: Apache License 2.0 5 votes vote down vote up
private JsonTransformer(Collection<Module> modules) {
    objectMapper = new ObjectMapper()
        .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
        .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
        .registerModule(new Jdk8Module())
        .registerModule(new JavaTimeModule())
        .registerModule(new GuavaModule())
        .registerModules(modules);
}
 
Example #18
Source Project: msf4j   Author: wso2   File: MSF4JJacksonDecoder.java    License: Apache License 2.0 4 votes vote down vote up
public MSF4JJacksonDecoder() {
    this(Collections.<Module>emptyList());
}
 
Example #19
Source Project: consensusj   Author: ConsensusJ   File: BitcoinConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public Module bitcoinJMapper(NetworkParameters params) {
    return new RpcServerModule(params);
}
 
Example #20
Source Project: micro-server   Author: aol   File: JacksonPlugin.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Set<Module> jacksonModules() {
    return SetX.of();
}
 
Example #21
Source Project: data-highway   Author: HotelsDotCom   File: PaverControllerConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public Module schemaSerializationModule() {
  return new SchemaSerializationModule();
}
 
Example #22
Source Project: feign   Author: OpenFeign   File: JacksonIteratorDecoder.java    License: Apache License 2.0 4 votes vote down vote up
public static JacksonIteratorDecoder create(Iterable<Module> modules) {
  return new JacksonIteratorDecoder(new ObjectMapper()
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .registerModules(modules));
}
 
Example #23
Source Project: heroic   Author: spotify   File: HeroicMappers.java    License: Apache License 2.0 4 votes vote down vote up
public static Module commonSerializers() {
    final SimpleModule serializers = new SimpleModule("common");
    serializers.addDeserializer(Duration.class, new DurationSerialization.Deserializer());
    serializers.addDeserializer(Groups.class, new GroupsSerialization.Deserializer());
    return serializers;
}
 
Example #24
Source Project: spring-boot-jpa-data-rest-soft-delete   Author: dzinot   File: JSONConfiguration.java    License: MIT License 4 votes vote down vote up
@Bean
public Module Jackson2HalModule() {
	return new Jackson2HalModule();
}
 
Example #25
Source Project: moserp   Author: thomasletsch   File: RestConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public Module jsr310Module() {
    return new JavaTimeModule();
}
 
Example #26
Source Project: jackson-modules-base   Author: FasterXML   File: ObjectMapperModule.java    License: Apache License 2.0 4 votes vote down vote up
public ObjectMapperModule registerModule(Key<? extends Module> key)
{
  modulesToInject.add(key);
  return this;
}
 
Example #27
Source Project: Eagle   Author: eBay   File: PolicyManager.java    License: Apache License 2.0 4 votes vote down vote up
public List<Module> getPolicyModules(String policyType){
	return policyModules.get(policyType);
}
 
Example #28
Source Project: camel-k-runtime   Author: apache   File: GenerateYamlLoaderSupportClasses.java    License: Apache License 2.0 4 votes vote down vote up
public final TypeSpec generateJacksonModule() {
    TypeSpec.Builder type = TypeSpec.classBuilder("YamlModule");
    type.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    type.superclass(Module.class);
    type.addMethod(
        MethodSpec.methodBuilder("getModuleName")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class)
            .returns(String.class)
            .addCode(CodeBlock.builder().addStatement("return $S", "camel-yaml").build())
            .build()
    );
    type.addMethod(
        MethodSpec.methodBuilder("version")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class)
            .returns(Version.class)
            .addCode(CodeBlock.builder().addStatement("return $L", "Version.unknownVersion()").build())
            .build()
    );

    MethodSpec.Builder mb = MethodSpec.methodBuilder("setupModule")
        .addModifiers(Modifier.PUBLIC)
        .addParameter(Module.SetupContext.class, "context");

    definitions(EXPRESSION_DEFINITION_CLASS).forEach(
        (k, v) -> mb.addStatement("context.registerSubtypes(new com.fasterxml.jackson.databind.jsontype.NamedType($L.class, $S))", v.getName(), k)
    );
    definitions(DATAFORMAT_DEFINITION_CLASS).forEach(
        (k, v) -> mb.addStatement("context.registerSubtypes(new com.fasterxml.jackson.databind.jsontype.NamedType($L.class, $S))", v.getName(), k)
    );
    definitions(LOAD_BALANCE_DEFINITION_CLASS).forEach(
        (k, v) -> mb.addStatement("context.registerSubtypes(new com.fasterxml.jackson.databind.jsontype.NamedType($L.class, $S))", v.getName(), k)
    );

    annotated(YAML_MIXIN_ANNOTATION).forEach(i -> {
        final AnnotationInstance annotation = i.classAnnotation(YAML_MIXIN_ANNOTATION);
        final AnnotationValue targets = annotation.value("value");

        String name = i.toString();
        if (i.nestingType() == ClassInfo.NestingType.INNER) {
            name = i.enclosingClass().toString() + "." + i.simpleName();
        }

        if (targets != null) {
            for (String target: targets.asStringArray()) {
                mb.addStatement("context.setMixInAnnotations($L.class, $L.class);", target, name);
            }
        }
    });


    type.addMethod(mb.build());

    return type.build();
}
 
Example #29
Source Project: spring-cloud-openfeign   Author: spring-cloud   File: FeignClientsConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Page")
public Module pageJacksonModule() {
	return new PageJacksonModule();
}
 
Example #30
Source Project: spring-cloud-openfeign   Author: spring-cloud   File: FeignClientsConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Page")
public Module sortModule() {
	return new SortJacksonModule();
}