com.fasterxml.jackson.databind.module.SimpleModule Java Examples

The following examples show how to use com.fasterxml.jackson.databind.module.SimpleModule. 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: JacksonIssue429Test.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testStackTraceElementWithCustom() throws Exception {
    // first, via bean that contains StackTraceElement
    final StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':'foobar'}"), StackTraceBean.class);
    Assert.assertNotNull(bean);
    Assert.assertNotNull(bean.location);
    Assert.assertEquals(StackTraceBean.NUM, bean.location.getLineNumber());

    // and then directly, iff registered
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule();
    module.addDeserializer(StackTraceElement.class, new Jackson429StackTraceElementDeserializer());
    mapper.registerModule(module);

    final StackTraceElement elem = mapper.readValue(
            aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}"),
            StackTraceElement.class);
    Assert.assertNotNull(elem);
    Assert.assertEquals(StackTraceBean.NUM, elem.getLineNumber());
}
 
Example #2
Source File: JsonSdlObjectMapper.java    From cm_ext with Apache License 2.0 6 votes vote down vote up
/**
 * We construct a new jackson object mapper for the parser since we want to
 * add some configuration that we don't want to apply to our global object
 * mapper. This object mapper has the following features:
 *
 * 1. Does not fail if there is an unknown element in the json file, by default.
 * It simply ignores the element and continues reading. This can be reconfigured.
 *
 * 2. We use Mr. Bean for bean materialization during deserialization. Mr Bean
 * uses ASM to create classes at runtime that conform to your abstract class
 * or interface. This allows us to define an immutable interface for the
 * service descriptor and not have to write out all the concrete classes.
 *
 * 3. We add mixin classes to the object mapper to let jackson know of
 * property name remaps.
 * @return
 */
private ObjectMapper createObjectMapper() {
  final Map<Class<?>, Class<?>> mixins = new HashMap<Class<?>, Class<?>>() {{
    put(Parameter.class, ParameterMixin.class);
    put(ConfigGenerator.class, GeneratorMixin.class);
    put(DependencyExtension.class, DependencyExtensionMixin.class);
    put(PlacementRuleDescriptor.class, PlacementRuleMixin.class);
    put(SslServerDescriptor.class, SslServerDescriptorTypeMixin.class);
    put(SslClientDescriptor.class, SslClientDescriptorTypeMixin.class);
  }};

  ObjectMapper m = new ObjectMapper();
  m.registerModule(new SimpleModule() {
    @Override
    public void setupModule(SetupContext context) {
      for (Entry<Class<?>, Class<?>> entry : mixins.entrySet()) {
        context.setMixInAnnotations(entry.getKey(), entry.getValue());
      }
    }
  });
  m.registerModule(new MrBeanModule());
  m.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
          false);
  m.configure(Feature.ALLOW_COMMENTS, true);
  return m;
}
 
Example #3
Source File: AdditionalPropertiesSerializer.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 serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            for (Class<?> c : TypeToken.of(beanDesc.getBeanClass()).getTypes().classes().rawTypes()) {
                if (c.isAssignableFrom(Object.class)) {
                    continue;
                }
                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 AdditionalPropertiesSerializer(beanDesc.getBeanClass(), serializer, mapper);
                        }
                    }
                }
            }
            return serializer;
        }
    });
    return module;
}
 
Example #4
Source File: ObjectMappers.java    From buck with Apache License 2.0 6 votes vote down vote up
private static ObjectMapper addCustomModules(ObjectMapper mapper, boolean intern) {
  // with this mixin UnconfiguredTargetNode properties are flattened with
  // UnconfiguredTargetNodeWithDeps
  // properties
  // for prettier view. It only works for non-typed serialization.
  mapper.addMixIn(
      UnconfiguredTargetNodeWithDeps.class,
      UnconfiguredTargetNodeWithDeps.UnconfiguredTargetNodeWithDepsUnwrappedMixin.class);

  // Serialize and deserialize UnconfiguredBuildTarget as string
  SimpleModule buildTargetModule = new SimpleModule("BuildTarget");
  buildTargetModule.addSerializer(UnconfiguredBuildTarget.class, new ToStringSerializer());
  buildTargetModule.addDeserializer(
      UnconfiguredBuildTarget.class,
      new FromStringDeserializer<UnconfiguredBuildTarget>(UnconfiguredBuildTarget.class) {
        @Override
        protected UnconfiguredBuildTarget _deserialize(
            String value, DeserializationContext ctxt) {
          return UnconfiguredBuildTargetParser.parse(value, intern);
        }
      });
  mapper.registerModule(buildTargetModule);
  mapper.registerModule(forwardRelativePathModule());
  return mapper;
}
 
Example #5
Source File: MarshallerService.java    From dawnsci with Eclipse Public License 1.0 6 votes vote down vote up
private final ObjectMapper createOldMapper() {

		ObjectMapper mapper = new ObjectMapper();

		// Use custom serialization for IPosition objects
		// (Otherwise all IPosition subclasses will need to become simple beans, i.e. no-arg constructors with getters
		// and setters for all fields. MapPosition.getNames() caused problems because it just returns keys from the map
		// and has no corresponding setter.)
		SimpleModule module = new SimpleModule();
		try { // Extension points might still work
			createModuleExtensions(module);
		} catch (Exception ne) {
			// Ignored, we allow the non-osgi mapper to continue without extension points.
		}
		mapper.registerModule(module);

		// Be careful adjusting these settings - changing them will probably cause various unit tests to fail which
		// check the exact contents of the serialized JSON string
		mapper.setSerializationInclusion(Include.NON_NULL);
		//mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
		return mapper;
	}
 
Example #6
Source File: GridMetadataContainer.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * JSON serializer for this object
 *
 * @return the network serialized
 * @throws SerializationException
 */
@JsonIgnore
public String toJSONString() throws it.eng.spagobi.commons.serializer.SerializationException {
	ObjectMapper mapper = new ObjectMapper();
	String s = "";
	try {
		SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null));
		simpleModule.addSerializer(GridMetadataContainer.class, new GridMetadataContainerJSONSerializer());
		mapper.registerModule(simpleModule);
		s = mapper.writeValueAsString(this);
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("Error while transforming into a JSON object", e);
	}
	// s = StringEscapeUtils.unescapeJavaScript(s);
	return s;
}
 
Example #7
Source File: ElasticsearchIO.java    From beam with Apache License 2.0 6 votes vote down vote up
@Setup
public void setup() throws IOException {
  ConnectionConfiguration connectionConfiguration = spec.getConnectionConfiguration();
  backendVersion = getBackendVersion(connectionConfiguration);
  restClient = connectionConfiguration.createClient();

  retryBackoff =
      FluentBackoff.DEFAULT.withMaxRetries(0).withInitialBackoff(RETRY_INITIAL_BACKOFF);

  if (spec.getRetryConfiguration() != null) {
    retryBackoff =
        FluentBackoff.DEFAULT
            .withInitialBackoff(RETRY_INITIAL_BACKOFF)
            .withMaxRetries(spec.getRetryConfiguration().getMaxAttempts() - 1)
            .withMaxCumulativeBackoff(spec.getRetryConfiguration().getMaxDuration());
  }
  // configure a custom serializer for metadata to be able to change serialization based
  // on ES version
  SimpleModule module = new SimpleModule();
  module.addSerializer(DocumentMetadata.class, new DocumentMetadataSerializer());
  OBJECT_MAPPER.registerModule(module);
}
 
Example #8
Source File: ParseCEF.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnScheduled
public void OnScheduled(final ProcessContext context) {

    // Configure jackson mapper before spawning onTriggers
    final SimpleModule module = new SimpleModule()
                                    .addSerializer(MacAddress.class, new MacAddressToStringSerializer());
    mapper.registerModule(module);
    mapper.setDateFormat(this.simpleDateFormat);

    switch (context.getProperty(TIME_REPRESENTATION).getValue()) {
        case LOCAL_TZ:
            // set the mapper TZ to local TZ
            mapper.setTimeZone(TimeZone.getDefault());
            tzId = TimeZone.getDefault().getID();
            break;
        case UTC:
            // set the mapper TZ to local TZ
            mapper.setTimeZone(TimeZone.getTimeZone(UTC));
            tzId = UTC;
            break;
    }

}
 
Example #9
Source File: RestObjectMapper.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public RestObjectMapper() {
  getFactory().disable(Feature.AUTO_CLOSE_SOURCE);
  // Enable features that can tolerance errors and not enable those make more constraints for compatible reasons.
  // Developers can use validation api to do more checks.
  disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  // no view annotations shouldn't be included in JSON
  disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
  disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
  enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

  SimpleModule module = new SimpleModule();
  // custom types
  module.addSerializer(JsonObject.class, new JsonObjectSerializer());
  registerModule(module);
  registerModule(new JavaTimeModule());
}
 
Example #10
Source File: AbstractStoresTest.java    From alfresco-simple-content-stores with Apache License 2.0 6 votes vote down vote up
/**
 * Configures and constructs a Resteasy client to use for calling the Alfresco Public ReST API in the dockerised deployment.
 *
 * @return the configured client
 */
protected static ResteasyClient setupResteasyClient()
{
    final SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new RestAPIBeanDeserializerModifier());

    final ResteasyJackson2Provider resteasyJacksonProvider = new ResteasyJackson2Provider();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.registerModule(module);
    resteasyJacksonProvider.setMapper(mapper);

    final LocalResteasyProviderFactory resteasyProviderFactory = new LocalResteasyProviderFactory(new ResteasyProviderFactoryImpl());
    resteasyProviderFactory.register(resteasyJacksonProvider);
    // will cause a warning regarding Jackson provider which is already registered
    RegisterBuiltin.register(resteasyProviderFactory);
    resteasyProviderFactory.register(new MultiValuedParamConverterProvider());

    final ResteasyClient client = new ResteasyClientBuilderImpl().providerFactory(resteasyProviderFactory).build();
    return client;
}
 
Example #11
Source File: WebConfig.java    From wetech-admin with MIT License 6 votes vote down vote up
@Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();

        //不显示为null的字段
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //序列化枚举是以ordinal()来输出
//        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, true);
        SimpleModule simpleModule = new SimpleModule();
//        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
//        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        //放到第一个
        converters.add(0, jackson2HttpMessageConverter);
    }
 
Example #12
Source File: JacksonRepoTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  final MongoDatabase database = context.database();
  this.collection = database.getCollection("jackson").withDocumentClass(BsonDocument.class);

  SimpleModule module = new SimpleModule(); // for our local serializers of Date and ObjectId
  module.addDeserializer(Date.class, new DateDeserializer());
  module.addSerializer(new DateSerializer());
  module.addDeserializer(ObjectId.class, new ObjectIdDeserializer());
  module.addSerializer(new ObjectIdSerializer());
  module.addDeserializer(UUID.class, new UUIDDeserializer(UuidRepresentation.JAVA_LEGACY));

  ObjectMapper mapper = new ObjectMapper()
      // to support bson types like: Document, BsonValue etc.
      .registerModule(JacksonCodecs.module(MongoClient.getDefaultCodecRegistry()))
      .registerModule(new GuavaModule())
      .registerModule(module);

  RepositorySetup setup = RepositorySetup.builder()
          .database(database)
          .codecRegistry(JacksonCodecs.registryFromMapper(mapper))
          .executor(MoreExecutors.newDirectExecutorService())
          .build();

  this.repository = new JacksonRepository(setup);
}
 
Example #13
Source File: RestClientConfig.java    From elastic-rest-spring-wrapper with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Autowired
public void configObjectMapper(ObjectMapper objectMapper) {
    AggregationDeserializer deserializer = new AggregationDeserializer();
    deserializer.register("sterms", TermsAggregation.class);
    deserializer.register("histogram", HistogramAggregation.class);
    deserializer.register("date_histogram", DateHistogramAggregation.class);
    deserializer.register("avg", SingleValueMetricsAggregation.class);
    deserializer.register("sum", SingleValueMetricsAggregation.class);
    deserializer.register("max", SingleValueMetricsAggregation.class);
    deserializer.register("min", SingleValueMetricsAggregation.class);
    deserializer.register("cardinality", SingleValueMetricsAggregation.class);
    deserializer.register("value_count", SingleValueMetricsAggregation.class);

    SimpleModule module = new SimpleModule("AggregationDeserializer",
            new Version(1, 0, 0, null, "eu.luminis.elastic", "aggregation-elastic"));
    module.addDeserializer(Aggregation.class, deserializer);
    module.addKeyDeserializer(String.class, new AggregationKeyDeserializer());

    objectMapper.registerModule(module);
}
 
Example #14
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 #15
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 #16
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 #17
Source File: VertxRestService.java    From atomix with Apache License 2.0 6 votes vote down vote up
protected ObjectMapper createObjectMapper() {
  ObjectMapper mapper = new ObjectMapper();

  mapper.setPropertyNamingStrategy(new ConfigPropertyNamingStrategy());
  mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
  mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
  mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
  mapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true);

  SimpleModule module = new SimpleModule("PolymorphicTypes");
  module.addDeserializer(PartitionGroupConfig.class, new PartitionGroupDeserializer(atomix.getRegistry()));
  module.addDeserializer(PrimitiveProtocolConfig.class, new PrimitiveProtocolDeserializer(atomix.getRegistry()));
  module.addDeserializer(PrimitiveConfig.class, new PrimitiveConfigDeserializer(atomix.getRegistry()));
  mapper.registerModule(module);

  return mapper;
}
 
Example #18
Source File: EntityFormatter.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static ObjectMapper createObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.setPropertyNamingStrategy(new EntitySetCamelCaseNamingStrategy());

    MixinUtils.addMixins(mapper);

    SimpleModule module = new SimpleModule();
    GeoJsonSerializer geoJsonSerializer = new GeoJsonSerializer();
    for (String encodingType : GeoJsonDeserializier.ENCODINGS) {
        CustomSerializationManager.getInstance().registerSerializer(encodingType, geoJsonSerializer);
    }

    module.addSerializer(Entity.class, new EntitySerializer());
    module.addSerializer(EntitySetResult.class, new EntitySetResultSerializer());
    module.addSerializer(TimeValue.class, new TimeValueSerializer());
    mapper.registerModule(module);
    return mapper;
}
 
Example #19
Source File: JacksonConfigParserTest.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void parseInvalidAudience() throws Exception {
    thrown.expect(InvalidAudienceCondition.class);
    String audienceString =
        "{" +
            "\"id\": \"123\"," +
            "\"name\":\"blah\"," +
            "\"conditions\":" +
            "\"[\\\"and\\\", [\\\"or\\\", [\\\"or\\\", \\\"123\\\"]]]\"" +
            "}";

    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Audience.class, new AudienceJacksonDeserializer(objectMapper));
    module.addDeserializer(Condition.class, new ConditionJacksonDeserializer(objectMapper));
    objectMapper.registerModule(module);

    Audience audience = objectMapper.readValue(audienceString, Audience.class);
    assertNotNull(audience);
    assertNotNull(audience.getConditions());
}
 
Example #20
Source File: TestStdSerializerOverrides.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public void testIntSerOverideNoAfterburner() throws Exception
{
    // First, baseline, no custom serializer
    assertEquals(aposToQuotes("{'value':42}"),
            VANILLA_MAPPER.writeValueAsString(new SimpleIntBean()));

    // and then with custom serializer, but no Afterburner
    String json = JsonMapper.builder()
            .addModule(new SimpleModule("module", Version.unknownVersion())
                .addSerializer(Integer.class, new MyIntSerializer())
                .addSerializer(Integer.TYPE, new MyIntSerializer()))
            .build()
            .writeValueAsString(new SimpleIntBean());
    assertEquals(aposToQuotes("{'value':-42}"), json);
}
 
Example #21
Source File: JSONUtils.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
public InternalObjectMapper ( ObjectMapper mapper)
{
    super( mapper );

    mapper.configure( JsonGenerator.Feature.IGNORE_UNKNOWN, true );
    mapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
    mapper.setSerializationInclusion( JsonInclude.Include.NON_EMPTY);

    SimpleModule module = new SimpleModule();
    module.addDeserializer( ProjectVersionRef.class, new ProjectVersionRefDeserializer());
    module.addSerializer(ProjectVersionRef.class, new ProjectVersionRefSerializer());
    module.addDeserializer( LookupReport.class, new LookupReportDeserializer() );
    mapper.registerModule( module );

}
 
Example #22
Source File: TestStdSerializerOverrides.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public void testLongSerOverideNoAfterburner() throws Exception
{
    // First, baseline, no custom serializer
    assertEquals(aposToQuotes("{'value':999}"),
            VANILLA_MAPPER.writeValueAsString(new SimpleLongBean()));

    // and then with custom serializer, but no Afterburner
    String json = JsonMapper.builder()
            .addModule(new SimpleModule("module", Version.unknownVersion())
                .addSerializer(Long.class, new MyLongSerializer())
                .addSerializer(Long.TYPE, new MyLongSerializer()))
            .build()
            .writeValueAsString(new SimpleLongBean());
    assertEquals(aposToQuotes("{'value':-999}"), json);
}
 
Example #23
Source File: VersionedJsonObjectMapper.java    From astrix with Apache License 2.0 5 votes vote down vote up
private <T> void registerSerializerAndDeserializer(ObjectMapper rawMapper,
												   ThreadLocal<Integer> versionHolder, 
												   SimpleModule module,
												   JsonMessageMigrator<T> migrator) {
	module.addSerializer(migrator.getJavaType(), MigratingJsonSerializer.create(rawMapper, migrator, versionHolder));
	module.addDeserializer(migrator.getJavaType(), MigratingJsonDeserializer.create(rawMapper, migrator, versionHolder));
}
 
Example #24
Source File: Allure1Plugin.java    From allure2 with Apache License 2.0 5 votes vote down vote up
public Allure1Plugin() {
    final SimpleModule module = new XmlParserModule()
            .addDeserializer(ru.yandex.qatools.allure.model.Status.class, new StatusDeserializer());
    xmlMapper = new XmlMapper()
            .configure(USE_WRAPPER_NAME_AS_PROPERTY_NAME, true)
            .setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()))
            .registerModule(module);
}
 
Example #25
Source File: KafkaConsumerOffsetFetcher.java    From eagle with Apache License 2.0 5 votes vote down vote up
public KafkaConsumerOffsetFetcher(ZKStateConfig config, String topic, String group) {
    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);
        this.topic = topic;
        this.group = group;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #26
Source File: JsonConverterIntegrationTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void constructor_with_customized_objectMapper_inherits_customization() {
    ObjectMapper jsonMapper = new ObjectMapper(new JsonFactory());
    SimpleModule module = new SimpleModule();
    module.addSerializer(TestData.class, new TestDataSerializer());
    jsonMapper.registerModule(module);
    JsonConverter jsonConverter = new JsonConverter(jsonMapper);
    assertThat(jsonConverter.writeValueAsString(new TestData())).isEqualTo("\"serialized by TestDataSerializer\"");
}
 
Example #27
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 #28
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 #29
Source File: ServletResponseResultWriter.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private static SimpleModule getWriteDateAndTimeAsStringModule() {
  JsonSerializer<DateAndTime> dateAndTimeSerializer = new JsonSerializer<DateAndTime>() {
    @Override
    public void serialize(DateAndTime value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException {
      jgen.writeString(value.toRfc3339String());
    }
  };
  SimpleModule writeDateAsStringModule = new SimpleModule("writeDateAsStringModule",
      new Version(1, 0, 0, null, null, null));
  writeDateAsStringModule.addSerializer(DateAndTime.class, dateAndTimeSerializer);
  return writeDateAsStringModule;
}
 
Example #30
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 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));
}