Java Code Examples for com.fasterxml.jackson.databind.module.SimpleModule#addSerializer()

The following examples show how to use com.fasterxml.jackson.databind.module.SimpleModule#addSerializer() . 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: DumpReportTask.java    From extract with MIT License 6 votes vote down vote up
/**
 * Dump the report as JSON to the given output stream.
 *
 * @param reportMap the report to dump
 * @param output the stream to dump to
 * @param match only dump matching results
 */
private void dump(final ReportMap reportMap, final OutputStream output, final ExtractionStatus match) throws
		IOException {
	final ObjectMapper mapper = new ObjectMapper();
	final SimpleModule module = new SimpleModule();

	module.addSerializer(ReportMap.class, new ReportSerializer(monitor, match));
	mapper.registerModule(module);

	try (final JsonGenerator jsonGenerator = new JsonFactory().setCodec(mapper).createGenerator(output,
			JsonEncoding.UTF8)) {
		jsonGenerator.useDefaultPrettyPrinter();
		jsonGenerator.writeObject(reportMap);
		jsonGenerator.writeRaw('\n');
	}
}
 
Example 2
Source File: GraphUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public static JSONArray serializeGraph(Query query) throws Exception {
	QueryGraph graph = query.getQueryGraph();
	if (graph != null) {
		logger.debug("The graph of the query is not null" + graph.toString());
		ObjectMapper mapper = new ObjectMapper();
		SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null));
		simpleModule.addSerializer(Relationship.class, new RelationJSONSerializerForAnalysisState());

		mapper.registerModule(simpleModule);
		String serialized = mapper.writeValueAsString(graph.getConnections());
		logger.debug("The serialization of the graph is " + serialized);
		JSONArray array = new JSONArray(serialized);
		return array;
	} else {
		logger.debug("The graph of the query is null");
		return new JSONArray();
	}

}
 
Example 3
Source File: MarshallerService.java    From dawnsci with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void applyMarshallersToModule(SimpleModule module, List<IMarshaller> marshallers) throws InstantiationException, IllegalAccessException {
	for (IMarshaller marshaller : marshallers) {
		Class<?> objectClass = marshaller.getObjectClass();
		if (objectClass!=null) {
			module.addSerializer(objectClass,  (JsonSerializer)marshaller.getSerializerClass().newInstance());
			module.addDeserializer(objectClass,(JsonDeserializer)marshaller.getDeserializerClass().newInstance());
		}

		Class<?> mixInType  = marshaller.getMixinAnnotationType();
		Class<?> mixInClass = marshaller.getMixinAnnotationClass();
		if (mixInClass!=null && mixInType!=null) {
			module.setMixInAnnotation(mixInType, mixInClass);
		}
	}
}
 
Example 4
Source File: Jackson2ObjectMapperBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // gh-22740
public void registerMultipleModulesWithNullTypeId() {
	Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
	SimpleModule fooModule = new SimpleModule();
	fooModule.addSerializer(new FooSerializer());
	SimpleModule barModule = new SimpleModule();
	barModule.addSerializer(new BarSerializer());
	builder.modulesToInstall(fooModule, barModule);
	ObjectMapper objectMapper = builder.build();
	assertEquals(1, StreamSupport
			.stream(getSerializerFactoryConfig(objectMapper).serializers().spliterator(), false)
			.filter(s -> s.findSerializer(null, SimpleType.construct(Foo.class), null) != null)
			.count());
	assertEquals(1, StreamSupport
			.stream(getSerializerFactoryConfig(objectMapper).serializers().spliterator(), false)
			.filter(s -> s.findSerializer(null, SimpleType.construct(Bar.class), null) != null)
			.count());
}
 
Example 5
Source File: JsonTranscoderTest.java    From simple-spring-memcached with MIT License 6 votes vote down vote up
@Test
public void testEncodeAndDecodeRegisterSerializerDirectlyToModule() {
    JsonObjectMapper mapper = new JsonObjectMapper();

    // first add serializer then register module
    SimpleModule module = new SimpleModule("cemo", Version.unknownVersion());
    module.addSerializer(Point.class, new PointSerializer());
    mapper.registerModule(module);

    transcoder = new JsonTranscoder(mapper);

    Point p = new Point(40, 50);

    CachedObject co = transcoder.encode(p);
    assertNotNull(co);
    assertNotNull(co.getData());
    assertEquals("{\"v\":\"40x50\"}", new String(co.getData()));
}
 
Example 6
Source File: ManagementConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.
            json().
            //propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE).
            propertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE).
            //featuresToEnable(SerializationFeature.INDENT_OUTPUT).
            //featuresToEnable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY).
            build();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Set.class,
            new StdDelegatingSerializer(Set.class, new StdConverter<Set, List>() {
                @Override
                public List convert(Set value) {
                    LinkedList list = new LinkedList(value);
                    Collections.sort(list);
                    return list;
                }
            })
    );
    objectMapper.registerModule(module);
    HttpMessageConverter c = new MappingJackson2HttpMessageConverter(
            objectMapper
    );
    converters.add(c);
}
 
Example 7
Source File: MonitorCenter.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * When the monitor starts, we initializes and registers a JSON module handling the serialization of
 * the monitor extension.
 */
@Validate
public void start() {
    module = new SimpleModule(MonitorExtension.class.getName());
    module.addSerializer(MonitorExtension.class, new JsonSerializer<MonitorExtension>() {
        @Override
        public void serialize(MonitorExtension monitorExtension, JsonGenerator jsonGenerator,
                              SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeStartObject();
            jsonGenerator.writeStringField("label", monitorExtension.label());
            jsonGenerator.writeStringField("url", monitorExtension.url());
            jsonGenerator.writeStringField("category", monitorExtension.category());
            jsonGenerator.writeEndObject();
        }
    });
    repository.register(module);
}
 
Example 8
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void setModules() {
	NumberSerializer serializer = new NumberSerializer(Integer.class);
	SimpleModule module = new SimpleModule();
	module.addSerializer(Integer.class, serializer);

	this.factory.setModules(Arrays.asList(new Module[]{module}));
	this.factory.afterPropertiesSet();
	ObjectMapper objectMapper = this.factory.getObject();

	Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next();
	assertSame(serializer, serializers.findSerializer(null, SimpleType.construct(Integer.class), null));
}
 
Example 9
Source File: DataExportCommand.java    From Cardshifter with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createMapper() {
    ObjectMapper mapper = CardshifterIO.mapper();
    SimpleModule module = new SimpleModule("ECSModule", new Version(0, 1, 0, "alpha", "com.cardshifter", "cardshifter"));
    module.addSerializer(Entity.class, new EntitySerializer());
    mapper.registerModule(module);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    return mapper;
}
 
Example 10
Source File: CustomObjectMapperSupplier.java    From hibernate-types with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectMapper get() {
    ObjectMapper objectMapper = new ObjectMapper().findAndRegisterModules();
    objectMapper.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null, null, null));
    simpleModule.addSerializer(new MoneySerializer());
    objectMapper.registerModule(simpleModule);
    return objectMapper;
}
 
Example 11
Source File: ObjectMapperFactory.java    From etf-webapp with European Union Public License 1.2 5 votes vote down vote up
public ObjectMapperFactory() {

        mapper.addMixIn(ModelItemDto.class, BaseMixin.class);
        mapper.addMixIn(Dto.class, BaseMixin.class);
        mapper.addMixIn(ExecutableTestSuiteDto.class, ExecutableTestSuiteDtoMixin.class);
        mapper.addMixIn(TranslationTemplateDto.class, TranslationTemplateMixin.class);
        mapper.addMixIn(TestObjectDto.class, TestObjectDtoMixin.class);

        // important!
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

        final FilterProvider filters = new SimpleFilterProvider().setDefaultFilter(baseFilter)
                .addFilter("translationTemplateFilter", translationTemplateFilter).addFilter("etsFilter", etsFilter)
                .addFilter("testObjectFilter", testObjectFilter);
        mapper.setFilterProvider(filters);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        final SimpleModule etfModule = new SimpleModule("EtfModule",
                new Version(1, 0, 0, null,
                        "de.interactive_instruments", "etf"));

        etfModule.addSerializer(EID.class, new EidConverter().jsonSerializer());
        etfModule.addDeserializer(EID.class, new EidConverter().jsonDeserializer());

        etfModule.addSerializer(de.interactive_instruments.Version.class, new VersionConverter().jsonSerializer());
        etfModule.addDeserializer(de.interactive_instruments.Version.class, new VersionConverter().jsonDeserializer());
        // Prevent XSS
        etfModule.addDeserializer(String.class, new JsonHtmlXssDeserializer());

        mapper.registerModule(etfModule);

        mapper.getFactory().setCharacterEscapes(new HTMLCharacterEscapes());
    }
 
Example 12
Source File: XssConfig.java    From runscore with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public ObjectMapper xssObjectMapper(Jackson2ObjectMapperBuilder builder) {
	ObjectMapper objectMapper = builder.createXmlMapper(false).build();
	SimpleModule xssModule = new SimpleModule();
	xssModule.addSerializer(new XssStringJsonSerializer());
	objectMapper.registerModule(xssModule);
	return objectMapper;
}
 
Example 13
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void setModules() {
	NumberSerializer serializer = new NumberSerializer(Integer.class);
	SimpleModule module = new SimpleModule();
	module.addSerializer(Integer.class, serializer);

	this.factory.setModules(Arrays.asList(new Module[]{module}));
	this.factory.afterPropertiesSet();
	ObjectMapper objectMapper = this.factory.getObject();

	Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next();
	assertSame(serializer, serializers.findSerializer(null, SimpleType.construct(Integer.class), null));
}
 
Example 14
Source File: ModelSerializationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private void validateJacksonSerialization(AllTypesRequest original) throws IOException {
    SimpleModule instantModule = new SimpleModule();
    instantModule.addSerializer(Instant.class, new InstantSerializer());
    instantModule.addDeserializer(Instant.class, new InstantDeserializer());

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(instantModule);

    String serialized = mapper.writeValueAsString(original.toBuilder());
    AllTypesRequest deserialized = mapper.readValue(serialized, AllTypesRequest.serializableBuilderClass()).build();
    assertThat(deserialized).isEqualTo(original);

}
 
Example 15
Source File: ConfigurationRequestSender.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ConfigurationRequestSender() {
  mapper = new ObjectMapper();
  SimpleModule module = new SimpleModule();
  module.addSerializer(HardwareAddress.class, new HardwareAddressSerializer());
  mapper.registerModule(module);
  mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
 
Example 16
Source File: PageHtmlContentRenderer.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createObjectMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    final SimpleModule mod = new SimpleModule("form module");
    mod.addSerializer(Form.class, new StdScalarSerializer<Form>(Form.class){
        @Override
        public void serialize(final Form value, final JsonGenerator gen, final SerializerProvider provider) throws IOException {
            gen.writeObject(value.data());
        }
    });
    mapper.registerModule(mod);
    return mapper;
}
 
Example 17
Source File: ControlTunnel.java    From Bats with Apache License 2.0 5 votes vote down vote up
public JacksonSerDe(Class<MSG> clazz, JsonSerializer<MSG> serializer, JsonDeserializer<MSG> deserializer) {
  ObjectMapper mapper = new ObjectMapper();
  SimpleModule module = new SimpleModule();
  mapper.registerModule(module);
  module.addSerializer(clazz, serializer);
  module.addDeserializer(clazz, deserializer);
  writer = mapper.writerFor(clazz);
  reader = mapper.readerFor(clazz);
}
 
Example 18
Source File: ProtoSerializers.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static <X> void registerPojo(SimpleModule module, Class<X> clazz) {
  Schema<X> schema = RuntimeSchema.getSchema(clazz);
  module.addDeserializer(clazz, new ProtostufStdDeserializer<>(clazz, schema));
  module.addSerializer(clazz, new ProtostufStdSerializer<>(clazz, schema));
}
 
Example 19
Source File: ObjectMapperBuilder.java    From moserp with Apache License 2.0 4 votes vote down vote up
private void registerQuantitySerializer(ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.addSerializer(Quantity.class, new BigDecimalWrapperSerializer());
    module.addSerializer(Price.class, new BigDecimalWrapperSerializer());
    mapper.registerModule(module);
}
 
Example 20
Source File: Base64UrlSerializer.java    From botbuilder-java with MIT License 2 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule() {
    SimpleModule module = new SimpleModule();
    module.addSerializer(Base64Url.class, new Base64UrlSerializer());
    return module;
}