List of usage examples for com.fasterxml.jackson.databind.module SimpleModule addDeserializer
public <T> SimpleModule addDeserializer(Class<T> type, JsonDeserializer<? extends T> deser)
From source file:org.elasticsoftware.elasticactors.base.serialization.ObjectMapperBuilder.java
private void registerCustomDeserializers(Reflections reflections, SimpleModule jacksonModule) { // @todo: looks like the SubTypeScanner only goes one level deep, need to fix this Set<Class<? extends StdScalarDeserializer>> customDeserializers = reflections .getSubTypesOf(StdScalarDeserializer.class); for (Class<? extends StdScalarDeserializer> customDeserializer : customDeserializers) { // need to exclude the JacksonActorRefDeserializer if (hasNoArgConstructor(customDeserializer)) { try { StdScalarDeserializer deserializer = customDeserializer.newInstance(); Class<?> objectClass = deserializer.handledType(); jacksonModule.addDeserializer(objectClass, deserializer); } catch (Exception e) { logger.error(String.format("Failed to create Custom Jackson Deserializer: %s", customDeserializer.getName()), e); }/*from www. ja v a2 s . co m*/ } else { // this ones can currently not be created by the scanner due to the special constructor for (Constructor<?> constructor : customDeserializer.getConstructors()) { if (hasSingleConstrutorParameterMatching(constructor, ActorRefFactory.class)) { try { StdScalarDeserializer deserializer = (StdScalarDeserializer) constructor .newInstance(actorRefFactory); Class<?> objectClass = deserializer.handledType(); jacksonModule.addDeserializer(objectClass, deserializer); break; } catch (Exception e) { logger.error(String.format("Failed to create Custom Jackson Deserializer: %s", customDeserializer.getName()), e); } } else if (hasSingleConstrutorParameterMatching(constructor, ScheduledMessageRefFactory.class)) { try { StdScalarDeserializer deserializer = (StdScalarDeserializer) constructor .newInstance(scheduledMessageRefFactory); Class<?> objectClass = deserializer.handledType(); jacksonModule.addDeserializer(objectClass, deserializer); break; } catch (Exception e) { logger.error(String.format("Failed to create Custom Jackson Deserializer: %s", customDeserializer.getName()), e); } } } } } }
From source file:com.evolveum.midpoint.prism.lex.json.AbstractJsonLexicalProcessor.java
private JsonParser configureParser(JsonParser parser) { ObjectMapper mapper = new ObjectMapper(); SimpleModule sm = new SimpleModule(); sm.addDeserializer(QName.class, new QNameDeserializer()); sm.addDeserializer(ItemPath.class, new ItemPathDeserializer()); sm.addDeserializer(PolyString.class, new PolyStringDeserializer()); sm.addDeserializer(ItemPathType.class, new ItemPathTypeDeserializer()); mapper.registerModule(sm);/*from w w w . jav a 2 s. c o m*/ parser.setCodec(mapper); return parser; }
From source file:org.broadleafcommerce.openadmin.web.service.FormBuilderServiceImpl.java
/** * When using Thymeleaf, we need to convert the JSON string back to * a DataWrapper object because Thymeleaf escapes JSON strings. * Thymeleaf uses it's own object de-serializer * see: https://github.com/thymeleaf/thymeleaf/issues/84 * see: http://forum.thymeleaf.org/Spring-Javascript-and-escaped-JSON-td4024739.html * @param json// ww w .java 2 s. c o m * @return DataWrapper * @throws IOException */ protected DataWrapper convertJsonToDataWrapper(String json) { ObjectMapper mapper = new ObjectMapper(); DataDTODeserializer dtoDeserializer = new DataDTODeserializer(); SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null, null, null)); module.addDeserializer(DataDTO.class, dtoDeserializer); mapper.registerModule(module); try { return mapper.readValue(json, DataWrapper.class); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.apache.drill.exec.store.parquet.Metadata.java
/** * Read the parquet metadata from a file * * @param path/* w ww. j ava 2 s .c om*/ * @return * @throws IOException */ private void readBlockMeta(String path, boolean dirsOnly, MetadataContext metaContext) throws IOException { Stopwatch timer = Stopwatch.createStarted(); Path p = new Path(path); Path parentDir = p.getParent(); // parent directory of the metadata file ObjectMapper mapper = new ObjectMapper(); final SimpleModule serialModule = new SimpleModule(); serialModule.addDeserializer(SchemaPath.class, new SchemaPath.De()); serialModule.addKeyDeserializer(ColumnTypeMetadata_v2.Key.class, new ColumnTypeMetadata_v2.Key.DeSerializer()); serialModule.addKeyDeserializer(ColumnTypeMetadata_v3.Key.class, new ColumnTypeMetadata_v3.Key.DeSerializer()); AfterburnerModule module = new AfterburnerModule(); module.setUseOptimizedBeanDeserializer(true); mapper.registerModule(serialModule); mapper.registerModule(module); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); FSDataInputStream is = fs.open(p); boolean alreadyCheckedModification = false; boolean newMetadata = false; if (metaContext != null) { alreadyCheckedModification = metaContext.getStatus(parentDir.toString()); } if (dirsOnly) { parquetTableMetadataDirs = mapper.readValue(is, ParquetTableMetadataDirs.class); logger.info("Took {} ms to read directories from directory cache file", timer.elapsed(TimeUnit.MILLISECONDS)); timer.stop(); if (!alreadyCheckedModification && tableModified(parquetTableMetadataDirs.getDirectories(), p, parentDir, metaContext)) { parquetTableMetadataDirs = (createMetaFilesRecursively( Path.getPathWithoutSchemeAndAuthority(p.getParent()).toString())).getRight(); newMetadata = true; } } else { parquetTableMetadata = mapper.readValue(is, ParquetTableMetadataBase.class); logger.info("Took {} ms to read metadata from cache file", timer.elapsed(TimeUnit.MILLISECONDS)); timer.stop(); if (!alreadyCheckedModification && tableModified(parquetTableMetadata.getDirectories(), p, parentDir, metaContext)) { parquetTableMetadata = (createMetaFilesRecursively( Path.getPathWithoutSchemeAndAuthority(p.getParent()).toString())).getLeft(); newMetadata = true; } // DRILL-5009: Remove the RowGroup if it is empty List<? extends ParquetFileMetadata> files = parquetTableMetadata.getFiles(); for (ParquetFileMetadata file : files) { List<? extends RowGroupMetadata> rowGroups = file.getRowGroups(); for (Iterator<? extends RowGroupMetadata> iter = rowGroups.iterator(); iter.hasNext();) { RowGroupMetadata r = iter.next(); if (r.getRowCount() == 0) { iter.remove(); } } } } if (newMetadata && metaContext != null) { // if new metadata files were created, invalidate the existing metadata context metaContext.clear(); } }
From source file:org.apache.tinkerpop.gremlin.structure.IoTest.java
/** * This is just a serialization check.//from w ww .j av a 2s . c o m */ @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); } }
From source file:org.pentaho.pdi.engine.serializers.DataEventSerializer.java
public DataEventSerializer() { super(DataEvent.class); SimpleModule module = new SimpleModule(); module.addSerializer(DataEvent.class, new JsonSerializer<DataEvent>() { @Override/*ww w. j a v a2 s. c o m*/ public void serialize(DataEvent dataEvent, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); Rows rows = (Rows) dataEvent.getData(); jsonGenerator.writeStringField("model-id", dataEvent.getSource().getId()); jsonGenerator.writeStringField("type", rows.getType().toString()); jsonGenerator.writeStringField("state", rows.getState().toString()); jsonGenerator.writeArrayFieldStart("rows"); for (Row row : rows) { jsonGenerator.writeStartObject(); jsonGenerator.writeArrayFieldStart("names"); for (String name : row.getColumnNames()) { jsonGenerator.writeString(name); } jsonGenerator.writeEndArray(); jsonGenerator.writeArrayFieldStart("objects"); for (Object obj : row.getObjects().get()) { jsonGenerator.writeStartObject(); if (obj == null) { jsonGenerator.writeStringField("type", "Null"); jsonGenerator.writeEndObject(); continue; } switch (obj.getClass().getSimpleName()) { case "String": jsonGenerator.writeStringField("type", "String"); jsonGenerator.writeStringField("obj", obj.toString()); break; case "Date": jsonGenerator.writeStringField("type", "Date"); jsonGenerator.writeStringField("obj", DATE_TIME_INSTANCE.format((Date) obj)); break; case "Integer": jsonGenerator.writeStringField("type", "Integer"); jsonGenerator.writeNumberField("obj", (Integer) obj); break; case "Long": jsonGenerator.writeStringField("type", "Long"); jsonGenerator.writeNumberField("obj", (Long) obj); break; case "Double": jsonGenerator.writeStringField("type", "Double"); jsonGenerator.writeNumberField("obj", (Double) obj); break; case "BigDecimal": jsonGenerator.writeStringField("type", "BigDecimal"); jsonGenerator.writeStringField("obj", obj.toString()); break; case "Boolean": jsonGenerator.writeStringField("type", "Boolean"); jsonGenerator.writeBooleanField("obj", (Boolean) obj); break; case "byte[]": jsonGenerator.writeStringField("type", "byte[]"); jsonGenerator.writeStringField("obj", new String(((byte[]) obj), "UTF-8")); break; default: if (obj instanceof Serializable) { jsonGenerator.writeStringField("type", "Object"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(obj); objectOutputStream.close(); outputStream.close(); byte[] bytes = outputStream.toByteArray(); jsonGenerator.writeStringField("obj", Base64.encodeBase64String(bytes)); } } jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); } }); module.addDeserializer(DataEvent.class, new StdNodeBasedDeserializer<DataEvent>(DataEvent.class) { @Override public DataEvent convert(JsonNode jsonNode, DeserializationContext deserializationContext) throws IOException { Rows.TYPE type = Rows.TYPE.valueOf(jsonNode.get("type").asText()); Rows.STATE state = Rows.STATE.valueOf(jsonNode.get("state").asText()); List<Row> rows = new ArrayList<>(); JsonNode json_rows = jsonNode.get("rows"); for (JsonNode row : json_rows) { List<Class> types = new ArrayList<>(); List<String> names = new ArrayList<>(); for (JsonNode name : row.get("names")) { names.add(name.asText()); } List<Object> objects = new ArrayList<>(); for (JsonNode obj : row.get("objects")) { JsonNode t = obj.get("type"); JsonNode rawObject = obj.get("obj"); Object object = null; String objType = t.asText(); switch (objType) { case "Null": types.add(Void.class); break; case "String": types.add(String.class); object = rawObject.asText(); break; case "Integer": types.add(Integer.class); object = rawObject.asInt(); break; case "Long": types.add(Long.class); object = rawObject.asLong(); break; case "Date": types.add(Date.class); try { object = DATE_TIME_INSTANCE.parse(rawObject.asText()); } catch (ParseException e) { e.printStackTrace(); } break; case "Double": types.add(Double.class); object = rawObject.asDouble(); break; case "BigDecimal": types.add(BigDecimal.class); object = new BigDecimal(rawObject.asText()); break; case "Boolean": types.add(Boolean.class); object = rawObject.asBoolean(); break; case "byte[]": types.add(byte[].class); object = rawObject.asText().getBytes("UTF-8"); break; case "Object": try { types.add(Object.class); object = new ObjectInputStream( new ByteArrayInputStream(Base64.decodeBase64(rawObject.asText()))) .readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } break; } objects.add(object); } Row r = new DeserializedRow(names, types, objects); rows.add(r); } Rows rowsObj = new Rows(rows, type, state); return new DataEvent(new RemoteSource(jsonNode.get("model-id").asText()), rowsObj); } }); mapper.registerModule(module); }