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

The following examples show how to use com.fasterxml.jackson.databind.module.SimpleModule#addDeserializer() . 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: SerializationDeserializationFeatureUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenCustomSerializerDeserializer_thanReadWriteCorrect() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleModule serializerModule = new SimpleModule("CustomSerializer", new Version(1, 0, 0, null, null, null));
    serializerModule.addSerializer(Car.class, new CustomCarSerializer());
    mapper.registerModule(serializerModule);
    final Car car = new Car("yellow", "renault");
    final String carJson = mapper.writeValueAsString(car);
    assertThat(carJson, containsString("renault"));
    assertThat(carJson, containsString("model"));

    final SimpleModule deserializerModule = new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null));
    deserializerModule.addDeserializer(Car.class, new CustomCarDeserializer());
    mapper.registerModule(deserializerModule);
    final Car carResult = mapper.readValue(EXAMPLE_JSON, Car.class);
    assertNotNull(carResult);
    assertThat(carResult.getColor(), equalTo("Black"));
}
 
Example 2
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 3
Source File: ObjectMappers.java    From buck with Apache License 2.0 6 votes vote down vote up
private static SimpleModule forwardRelativePathModule() {
  SimpleModule module = new SimpleModule();
  module.addSerializer(ForwardRelativePath.class, new ToStringSerializer());
  module.addDeserializer(
      ForwardRelativePath.class,
      new FromStringDeserializer<ForwardRelativePath>(ForwardRelativePath.class) {
        @Override
        protected ForwardRelativePath _deserialize(String value, DeserializationContext ctxt)
            throws IOException {
          return ForwardRelativePath.of(value);
        }

        @Override
        protected ForwardRelativePath _deserializeFromEmptyString() throws IOException {
          return ForwardRelativePath.EMPTY;
        }
      });
  return module;
}
 
Example 4
Source File: JacksonConfigParserTest.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void parseTypedAudienceLeaf() throws Exception {
    String audienceString =
        "{" +
            "\"id\": \"3468206645\"," +
            "\"name\": \"DOUBLE\"," +
            "\"conditions\": {\"name\": \"doubleKey\", \"type\": \"custom_attribute\", \"match\":\"lt\", \"value\":100.0}" +
            "},";

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

    Audience audience = objectMapper.readValue(audienceString, TypedAudience.class);
    assertNotNull(audience);
    assertNotNull(audience.getConditions());
}
 
Example 5
Source File: GooglePlusTypeConverterIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setup() {
  objectMapper = StreamsJacksonMapper.getInstance();
  SimpleModule simpleModule = new SimpleModule();
  simpleModule.addDeserializer(Person.class, new GPlusPersonDeserializer());
  simpleModule.addDeserializer(com.google.api.services.plus.model.Activity.class, new GPlusActivityDeserializer());
  objectMapper.registerModule(simpleModule);
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

  googlePlusTypeConverter = new GooglePlusTypeConverter();
  googlePlusTypeConverter.prepare(null);
}
 
Example 6
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 7
Source File: OAuthPublicKeyStore.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
private ObjectMapper createObjectMapper() {
    ObjectMapper newObjectMapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(ZonedDateTime.class, new ZonedDateTimeDeserializer());
    newObjectMapper.registerModule(module);
    return newObjectMapper;
}
 
Example 8
Source File: DefaultMapperFactory.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
public ObjectMapper instance(HarReaderMode mode) {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    if (mode == HarReaderMode.LAX) {
        module.addDeserializer(Date.class, new ExceptionIgnoringDateDeserializer());
        module.addDeserializer(Integer.class, new ExceptionIgnoringIntegerDeserializer());
    }
    mapper.registerModule(module);
    return mapper;
}
 
Example 9
Source File: StackTraceElementYamlMixInTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromYamlWithSimpleModule() throws Exception {
    final ObjectMapper mapper = new YAMLMapper();
    final SimpleModule module = new SimpleModule();
    module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java",
            123);
    final StackTraceElement actual = mapper.readValue(
            "---\nclass: package.SomeClass\nmethod: someMethod\nfile: SomeClass.java\nline: 123\n...",
            StackTraceElement.class);
    Assert.assertEquals(expected, actual);
}
 
Example 10
Source File: DefaultServiceSpecTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testGoalStateDeserializesOldValues() throws Exception {
    ObjectMapper objectMapper = SerializationUtils.registerDefaultModules(new ObjectMapper());
    DefaultServiceSpec.ConfigFactory.GoalStateDeserializer goalStateDeserializer =
            new DefaultServiceSpec.ConfigFactory.GoalStateDeserializer();

    SimpleModule module = new SimpleModule();
    module.addDeserializer(GoalState.class, goalStateDeserializer);
    objectMapper.registerModule(module);

    Assert.assertEquals(
            GoalState.ONCE, SerializationUtils.fromString("\"ONCE\"", GoalState.class, objectMapper));
    Assert.assertEquals(
            GoalState.ONCE, SerializationUtils.fromString("\"FINISHED\"", GoalState.class, objectMapper));
}
 
Example 11
Source File: JacksonHelper.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper create() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    SimpleModule module = new SimpleModule();
    module.addDeserializer(Pageable.class, new JsonablePage.PageableDeserializer());
    mapper.registerModule(module);

    return mapper;
}
 
Example 12
Source File: Model.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
protected static ObjectMapper createMapper() {
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    final SimpleModule module = new SimpleModule();
    module.addDeserializer(AbstractNode.class, new NodeDeserializer());
    mapper.registerModule(module);
    return mapper;
}
 
Example 13
Source File: TopologySerdes.java    From kafka-topology-builder with MIT License 5 votes vote down vote up
public TopologySerdes() {
  mapper = new ObjectMapper(new YAMLFactory());
  SimpleModule module = new SimpleModule();
  module.addDeserializer(Topology.class, new TopologyCustomDeserializer());
  module.addDeserializer(Project.class, new ProjectCustomDeserializer());
  mapper.registerModule(module);
  mapper.registerModule(new Jdk8Module());
  mapper.findAndRegisterModules();
}
 
Example 14
Source File: StackTraceElementYamlMixInTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromYamlWithLog4jModule() throws Exception {
    final ObjectMapper mapper = new YAMLMapper();
    final boolean encodeThreadContextAsList = false;
    final SimpleModule module = new Log4jYamlModule(encodeThreadContextAsList, true, false);
    module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java",
            123);
    final StackTraceElement actual = mapper.readValue(
            "---\nclass: package.SomeClass\nmethod: someMethod\nfile: SomeClass.java\nline: 123\n...",
            StackTraceElement.class);
    Assert.assertEquals(expected, actual);
}
 
Example 15
Source File: SimpleModuleInitializer.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public void initialize(final SimpleModule simpleModule, final boolean objectMessageAsJsonObject) {
    // Workaround because mix-ins do not work for classes that already have a built-in deserializer.
    // See Jackson issue 429.
    simpleModule.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    simpleModule.addDeserializer(ContextStack.class, new MutableThreadContextStackDeserializer());
    if (objectMessageAsJsonObject) {
        simpleModule.addSerializer(ObjectMessage.class, new ObjectMessageSerializer());
    }
    simpleModule.addSerializer(Message.class, new MessageSerializer());
}
 
Example 16
Source File: Metadata.java    From Bats with Apache License 2.0 4 votes vote down vote up
/**
 * Reads the summary from the metadata cache file, if the cache file is stale recreates the metadata
 * @param fs
 * @param metadataParentDir
 * @param autoRefreshTriggered true if the auto-refresh is already triggered
 * @param readerConfig
 * @return returns metadata summary
 */
public static Metadata_V4.MetadataSummary getSummary(FileSystem fs, Path metadataParentDir, boolean autoRefreshTriggered, ParquetReaderConfig readerConfig) {
  Path summaryFile = getSummaryFileName(metadataParentDir);
  Path metadataDirFile = getDirFileName(metadataParentDir);
  MetadataContext metaContext = new MetadataContext();
  try {
    // If autoRefresh is not triggered and none of the metadata files exist
    if (!autoRefreshTriggered && !metadataExists(fs, metadataParentDir)) {
      logger.debug("Metadata doesn't exist in {}", metadataParentDir);
      return null;
    } else if (autoRefreshTriggered && !fs.exists(summaryFile)) {
      logger.debug("Metadata Summary file {} does not exist", summaryFile);
      return null;
    } else {
      // If the autorefresh is not triggered, check if the cache file is stale and trigger auto-refresh
      if (!autoRefreshTriggered) {
        Metadata metadata = new Metadata(readerConfig);
        if (!fs.exists(metadataDirFile)) {
          return null;
        }
        ParquetTableMetadataDirs metadataDirs  = readMetadataDirs(fs, metadataDirFile, metaContext, readerConfig);
        if (metadata.tableModified(metadataDirs.getDirectories(), summaryFile, metadataParentDir, metaContext, fs) && true) {
          ParquetTableMetadata_v4 parquetTableMetadata = (metadata.createMetaFilesRecursivelyAsProcessUser(Path.getPathWithoutSchemeAndAuthority(summaryFile.getParent()), fs, true, null, true)).getLeft();
          return parquetTableMetadata.getSummary();
        }
      }
      // Read the existing metadataSummary cache file to get the metadataSummary
      ObjectMapper mapper = new ObjectMapper();
      final SimpleModule serialModule = new SimpleModule();
      serialModule.addDeserializer(SchemaPath.class, new SchemaPath.De());
      serialModule.addKeyDeserializer(ColumnTypeMetadata_v4.Key.class, new ColumnTypeMetadata_v4.Key.DeSerializer());
      AfterburnerModule module = new AfterburnerModule();
      module.setUseOptimizedBeanDeserializer(true);
      mapper.registerModule(serialModule);
      mapper.registerModule(module);
      mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      InputStream is = fs.open(summaryFile);
      Metadata_V4.MetadataSummary metadataSummary = mapper.readValue(is, Metadata_V4.MetadataSummary.class);
      return metadataSummary;
      }
  } catch (IOException e) {
    logger.debug("Failed to read '{}' summary metadata file", summaryFile, e);
    return null;
  }
}
 
Example 17
Source File: DefaultJsonService.java    From imagej-server with Apache License 2.0 4 votes vote down vote up
@Override
public void addDeserializerTo(final ObjectMapper objectMapper) {
	final SimpleModule module = new SimpleModule();
	module.addDeserializer(Object.class, idToObjDeserializer);
	objectMapper.registerModule(module);
}
 
Example 18
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 4 votes vote down vote up
@Test
public void testComplexArrayWithExample() throws Exception {
    Map<String, Schema> definitions = new HashMap<>();

    Schema address = new Schema()
      .example("{\"foo\":\"bar\"}")
      .xml(new XML()
        .name("address"));

    Schema propertyDefinition1 = new StringSchema();
    propertyDefinition1.setName("street");
    propertyDefinition1.setExample("12345 El Monte Blvd");

    Schema propertyDefinition2 = new StringSchema();
    propertyDefinition2.setName("city");
    propertyDefinition2.setExample("Los Altos Hills");

    Schema propertyDefinition3 = new StringSchema();
    propertyDefinition3.setName("state");
    propertyDefinition3.setExample("CA");
    propertyDefinition3.setMinLength(2);
    propertyDefinition3.setMaxLength(2);

    Schema propertyDefinition4 = new StringSchema();
    propertyDefinition4.setName("zip");
    propertyDefinition4.setExample("94022");

    address.addProperties("street",propertyDefinition1);
    address.addProperties("city",propertyDefinition2);
    address.addProperties("state",propertyDefinition3);
    address.addProperties("zip",propertyDefinition4);


    definitions.put("Address", address);

    // register the JSON serializer
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(new JsonNodeExampleSerializer());
    simpleModule.addDeserializer(Example.class, new JsonExampleDeserializer());
    Json.mapper().registerModule(simpleModule);

    Example rep = (Example) ExampleBuilder.fromSchema(new StringSchema().addEnumItem("hello").example("fun"), definitions);
    assertEqualsIgnoreLineEnding(Json.pretty(rep), "\"fun\"");
}
 
Example 19
Source File: Jackson2ObjectMapperBuilder.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> void addDeserializers(SimpleModule module) {
	for (Class<?> type : this.deserializers.keySet()) {
		module.addDeserializer((Class<T>) type, (JsonDeserializer<? extends T>) this.deserializers.get(type));
	}
}
 
Example 20
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));
}