List of usage examples for com.fasterxml.jackson.databind.module SimpleModule addSerializer
public <T> SimpleModule addSerializer(Class<? extends T> type, JsonSerializer<T> ser)
From source file:org.elasticsoftware.elasticactors.base.serialization.ObjectMapperBuilder.java
private void registerCustomSerializers(Reflections reflections, SimpleModule jacksonModule) { Set<Class<? extends JsonSerializer>> customSerializers = reflections.getSubTypesOf(JsonSerializer.class); for (Class<? extends JsonSerializer> customSerializer : customSerializers) { Class<?> objectClass = TypeResolver.resolveRawArgument(JsonSerializer.class, customSerializer); try {/* w ww.jav a2s. co m*/ jacksonModule.addSerializer(objectClass, customSerializer.newInstance()); } catch (Exception e) { logger.warn( String.format("Failed to create Custom Jackson Serializer: %s", customSerializer.getName()), e); } } }
From source file:org.mongojack.TestCustomObjectMapper.java
private ObjectMapper createObjectMapper() { SimpleModule module = new SimpleModule("MySimpleModule", new Version(1, 0, 0, null, "", "")); module.addDeserializer(Custom.class, new JsonDeserializer<Custom>() { @Override/*from w ww . j ava2 s . c o m*/ public Custom deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.readValueAsTree(); return new Custom(node.get("v1").asText(), node.get("v2").asText()); } }); module.addSerializer(Custom.class, new JsonSerializer<Custom>() { @Override public void serialize(Custom value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); jgen.writeFieldName("v1"); jgen.writeString(value.value1); jgen.writeFieldName("v2"); jgen.writeString(value.value2); jgen.writeEndObject(); } }); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(module); MongoJackModule.configure(objectMapper); return objectMapper; }
From source file:io.qdb.server.controller.JsonService.java
private ObjectMapper createMapper(boolean prettyPrint, boolean datesAsTimestamps, boolean borg) { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); mapper.configure(SerializationFeature.INDENT_OUTPUT, prettyPrint); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, datesAsTimestamps); SimpleModule module = new SimpleModule(); module.addDeserializer(Date.class, dateDeserializer); module.addDeserializer(Integer.class, integerJsonDeserializer); module.addDeserializer(Integer.TYPE, integerJsonDeserializer); module.addDeserializer(Long.class, longJsonDeserializer); module.addDeserializer(Long.TYPE, longJsonDeserializer); if (!borg) {/*w ww.j ava2s.c om*/ module.addSerializer(Integer.TYPE, integerSerializer); module.addSerializer(Integer.class, integerSerializer); module.addSerializer(Long.TYPE, longSerializer); module.addSerializer(Long.class, longSerializer); } if (!datesAsTimestamps) module.addSerializer(Date.class, new ISO8601DateSerializer()); mapper.registerModule(module); return mapper; }
From source file:com.logsniffer.event.es.EsEventPersistence.java
@PostConstruct private void initJsonMapper() { jsonMapper = new ObjectMapper(); jsonMapper.configure(MapperFeature.USE_STATIC_TYPING, true); jsonMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); jsonMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.registerSubtypes(LogEntry.class); final SimpleModule esModule = new SimpleModule(); esModule.addSerializer(LogPointer.class, new EsLogPointerSerializer()); esModule.addDeserializer(LogPointer.class, new EsLogPointerDeserializer()); esModule.addDeserializer(JsonLogPointer.class, new EsLogPointerDeserializer()); jsonMapper.registerModule(esModule); }
From source file:com.rcv.ResultsWriter.java
private void generateSummaryJson(Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct, String outputPath) throws IOException { // mapper converts java objects to json ObjectMapper mapper = new ObjectMapper(); // set mapper to order keys alphabetically for more legible output mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); // create a module to contain a serializer for BigDecimal serialization SimpleModule module = new SimpleModule(); module.addSerializer(BigDecimal.class, new ToStringSerializer()); // attach serializer to mapper mapper.registerModule(module);/*from w w w.j av a 2 s .c om*/ // jsonWriter writes those object to disk ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter()); // jsonPath for output json summary String jsonPath = outputPath + ".json"; // log output location Logger.log(Level.INFO, "Generating summary JSON file: %s...", jsonPath); // outFile is the target file File outFile = new File(jsonPath); // root outputJson dict will have two entries: // results - vote totals, transfers, and candidates elected / eliminated // config - global config into HashMap<String, Object> outputJson = new HashMap<>(); // config will contain contest configuration info HashMap<String, Object> configData = new HashMap<>(); // add config header info configData.put("contest", config.getContestName()); configData.put("jurisdiction", config.getContestJurisdiction()); configData.put("office", config.getContestOffice()); configData.put("date", config.getContestDate()); configData.put("threshold", winningThreshold); if (precinct != null && !precinct.isEmpty()) { configData.put("precinct", precinct); } // results will be a list of round data objects ArrayList<Object> results = new ArrayList<>(); // for each round create objects for json serialization for (int round = 1; round <= numRounds; round++) { // container for all json data this round: HashMap<String, Object> roundData = new HashMap<>(); // add round number (this is implied by the ordering but for debugging we are explicit) roundData.put("round", round); // add actions if this is not a precinct summary if (precinct == null || precinct.isEmpty()) { // actions is a list of one or more action objects ArrayList<Object> actions = new ArrayList<>(); addActionObjects("elected", roundToWinningCandidates.get(round), round, actions); // add any elimination actions addActionObjects("eliminated", roundToEliminatedCandidates.get(round), round, actions); // add action objects roundData.put("tallyResults", actions); } // add tally object roundData.put("tally", updateCandidateNamesInTally(roundTallies.get(round))); // add roundData to results list results.add(roundData); } // add config data to root object outputJson.put("config", configData); // add results to root object outputJson.put("results", results); // write results to disk try { jsonWriter.writeValue(outFile, outputJson); } catch (IOException exception) { Logger.log(Level.SEVERE, "Error writing to JSON file: %s\n%s", jsonPath, exception.toString()); throw exception; } }
From source file:org.apache.drill.exec.store.parquet.metadata.Metadata.java
/** * Serialize parquet metadata to json and write to a file. * * @param parquetTableMetadata parquet table metadata * @param p file path//from www. j a v a 2 s . co m */ private void writeFile(ParquetTableMetadata_v3 parquetTableMetadata, Path p, FileSystem fs) throws IOException { JsonFactory jsonFactory = new JsonFactory(); jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false); jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false); ObjectMapper mapper = new ObjectMapper(jsonFactory); SimpleModule module = new SimpleModule(); module.addSerializer(ColumnMetadata_v3.class, new ColumnMetadata_v3.Serializer()); mapper.registerModule(module); FSDataOutputStream os = fs.create(p); mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadata); os.flush(); os.close(); }
From source file:io.gravitee.management.rest.mapper.ObjectMapperResolver.java
public ObjectMapperResolver() { mapper = new GraviteeMapper(); SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override//from w ww .j a va 2 s . co m public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config, final JavaType type, BeanDescription beanDesc, final JsonDeserializer<?> deserializer) { return new JsonDeserializer<Enum>() { @Override public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase()); } }; } }); module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) { @Override public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeString(value.name().toLowerCase()); } }); mapper.registerModule(module); }
From source file:org.apache.drill.exec.store.parquet.Metadata.java
/** * Serialize parquet metadata to json and write to a file * * @param parquetTableMetadata/*from w ww . ja v a 2s .c om*/ * @param p * @throws IOException */ private void writeFile(ParquetTableMetadata_v3 parquetTableMetadata, Path p) throws IOException { JsonFactory jsonFactory = new JsonFactory(); jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false); jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false); ObjectMapper mapper = new ObjectMapper(jsonFactory); SimpleModule module = new SimpleModule(); module.addSerializer(ColumnMetadata_v3.class, new ColumnMetadata_v3.Serializer()); mapper.registerModule(module); FSDataOutputStream os = fs.create(p); mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadata); os.flush(); os.close(); }
From source file:org.apache.tinkerpop.gremlin.structure.IoTest.java
/** * This is just a serialization check.//from w w w . jav a2 s. c om */ @Test @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_ANY_IDS) public void shouldProperlySerializeDeserializeCustomIdWithGraphSON() throws Exception { final UUID id = UUID.fromString("AF4B5965-B176-4552-B3C1-FBBE2F52C305"); g.addVertex(T.id, new CustomId("vertex", id)); final SimpleModule module = new SimpleModule(); module.addSerializer(CustomId.class, new CustomId.CustomIdJacksonSerializer()); module.addDeserializer(CustomId.class, new CustomId.CustomIdJacksonDeserializer()); final GraphWriter writer = g.io().graphSONWriter() .mapper(g.io().graphSONMapper().addCustomModule(module).embedTypes(true).create()).create(); try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { writer.writeGraph(baos, g); final JsonNode jsonGraph = new ObjectMapper().readTree(baos.toByteArray()); final JsonNode onlyVertex = jsonGraph.findValues(GraphSONTokens.VERTICES).get(0).get(0); final JsonNode idValue = onlyVertex.get(GraphSONTokens.ID); assertTrue(idValue.has("cluster")); assertEquals("vertex", idValue.get("cluster").asText()); assertTrue(idValue.has("elementId")); assertEquals("AF4B5965-B176-4552-B3C1-FBBE2F52C305".toLowerCase(), idValue.get("elementId").asText()); // reusing the same config used for creation of "g". final Configuration configuration = graphProvider.newGraphConfiguration("g2", this.getClass(), name.getMethodName()); graphProvider.clear(configuration); final Graph g2 = graphProvider.openTestGraph(configuration); try (final InputStream is = new ByteArrayInputStream(baos.toByteArray())) { final GraphReader reader = g.io().graphSONReader() .mapper(g.io().graphSONMapper().embedTypes(true).addCustomModule(module).create()).create(); reader.readGraph(is, g2); } final Vertex v2 = g2.V().next(); final CustomId customId = (CustomId) v2.id(); assertEquals(id, customId.getElementId()); assertEquals("vertex", customId.getCluster()); // need to manually close the "g2" instance graphProvider.clear(g2, configuration); } }