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.brutusin.json.impl.JacksonCodec.java
public JacksonCodec(ObjectMapper mapper, JacksonFactoryWrapper schemaFactory) { if (mapper == null) { mapper = new ObjectMapper(); mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleModule testModule = new SimpleModule("json-provider-module", new Version(1, 0, 0, null, "org.brutusin", "json-provider")); testModule.addSerializer(new JsonNodeSerializer()); testModule.addDeserializer(JsonNode.class, new JsonNodeDeserializer()); testModule.addSerializer(new InputStreamSerializer()); testModule.addDeserializer(InputStream.class, new InputStreamDeserializer()); testModule.addDeserializer(MetaDataInputStream.class, new InputStreamDeserializer()); mapper.registerModule(testModule); }// ww w . j a v a 2 s . c o m if (schemaFactory == null) { schemaFactory = new JacksonFactoryWrapper(new HashMap<Class, String>(DEFAULT_FORMAT_MAP)); } this.mapper = mapper; this.schemaFactory = schemaFactory; }
From source file:io.seldon.api.state.ClientAlgorithmStore.java
@Override public void configUpdated(String client, String configKey, String configValue) { SimpleModule module = new SimpleModule("StrategyDeserializerModule"); module.addDeserializer(Strategy.class, new StrategyDeserializer()); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module);/* ww w . j a v a 2 s . com*/ if (configKey.equals(ALG_KEY)) { logger.info("Received new algorithm config for " + client + ": " + configValue); try { List<AlgorithmStrategy> strategies = new ArrayList<>(); Map<String, AlgorithmStrategy> stratMap = new HashMap<>(); AlgorithmConfig config = mapper.readValue(configValue, AlgorithmConfig.class); for (Algorithm algorithm : config.algorithms) { AlgorithmStrategy strategy = toAlgorithmStrategy(algorithm); strategies.add(strategy); } AlgorithmResultsCombiner combiner = applicationContext.getBean(config.combiner, AlgorithmResultsCombiner.class); Map<Integer, Double> actionWeightMap = toActionWeightMap(config.actionWeights); store.put(client, new SimpleClientStrategy(Collections.unmodifiableList(strategies), combiner, config.diversityLevel, ClientStrategy.DEFAULT_NAME, actionWeightMap)); storeMap.put(client, Collections.unmodifiableMap(stratMap)); logger.info("Successfully added new algorithm config for " + client); } catch (IOException | BeansException e) { logger.error("Couldn't update algorithms for client " + client, e); } } else if (configKey.equals(TESTING_SWITCH_KEY)) { // not json as its so simple Boolean onOff = BooleanUtils.toBooleanObject(configValue); if (onOff == null) { logger.error("Couldn't set testing switch for client " + client + ", input was " + configValue); } else { logger.info("Testing switch for client " + client + " moving from '" + BooleanUtils.toStringOnOff(testingOnOff.get(client)) + "' to '" + BooleanUtils.toStringOnOff(onOff) + "'"); testingOnOff.put(client, BooleanUtils.toBooleanObject(configValue)); } } else if (configKey.equals(TEST)) { logger.info("Received new testing config for " + client + ":" + configValue); try { TestConfig config = mapper.readValue(configValue, TestConfig.class); List<VariationTestingClientStrategy.Variation> variations = new ArrayList<>(); for (TestVariation var : config.variations) { List<AlgorithmStrategy> strategies = new ArrayList<>(); for (Algorithm alg : var.config.algorithms) { AlgorithmStrategy strategy = toAlgorithmStrategy(alg); strategies.add(strategy); } AlgorithmResultsCombiner combiner = applicationContext.getBean(var.config.combiner, AlgorithmResultsCombiner.class); Map<Integer, Double> actionWeightMap = toActionWeightMap(var.config.actionWeights); variations.add(new VariationTestingClientStrategy.Variation( new SimpleClientStrategy(Collections.unmodifiableList(strategies), combiner, var.config.diversityLevel, var.label, actionWeightMap), new BigDecimal(var.ratio))); } tests.put(client, VariationTestingClientStrategy.build(variations)); logger.info("Succesfully added " + variations.size() + " variation test for " + client); } catch (NumberFormatException | IOException e) { logger.error("Couldn't add test for client " + client, e); } } else if (configKey.equals(RECTAG)) { logger.info("Received new rectag config for " + client + ": " + configValue); try { RecTagConfig config = mapper.readValue(configValue, RecTagConfig.class); if (config.defaultStrategy == null) { logger.error("Couldn't read rectag config as there was no default alg"); return; } ClientStrategy defStrategy = toStrategy(config.defaultStrategy); Map<String, ClientStrategy> recTagStrats = new HashMap<>(); for (Map.Entry<String, Strategy> entry : config.recTagToStrategy.entrySet()) { recTagStrats.put(entry.getKey(), toStrategy(entry.getValue())); } recTagStrategies.put(client, new RecTagClientStrategy(defStrategy, recTagStrats)); logger.info("Successfully added rec tag strategy for " + client); } catch (NumberFormatException | IOException e) { logger.error("Couldn't add rectag strategy for client " + client, e); } } }
From source file:de.undercouch.bson4jackson.BsonParserTest.java
/** * Check if org.bson.types.ObjectId can be serialized and deserialized as * a byte array. See issue #38/*from w w w. j a v a2 s . co m*/ * @throws Exception if something goes wrong */ @Test public void parseObjectId() throws Exception { class ObjectIdDeserializer extends StdDeserializer<org.bson.types.ObjectId> { private static final long serialVersionUID = 6934309887169924897L; protected ObjectIdDeserializer() { super(org.bson.types.ObjectId.class); } @Override public org.bson.types.ObjectId deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonGenerationException { return new org.bson.types.ObjectId(jp.getBinaryValue()); } } org.bson.types.ObjectId oid = new org.bson.types.ObjectId(); BSONObject o = new BasicBSONObject(); o.put("oid", oid.toByteArray()); SimpleModule mod = new SimpleModule(); mod.addDeserializer(org.bson.types.ObjectId.class, new ObjectIdDeserializer()); ObjectIdClass res = parseBsonObject(o, ObjectIdClass.class, mod); assertEquals(oid, res.oid); }
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:org.openmhealth.shim.healthvault.HealthvaultShim.java
@Override public ShimDataResponse getData(final ShimDataRequest shimDataRequest) throws ShimException { final HealthVaultDataType healthVaultDataType; try {/*w ww . jav a 2 s . c om*/ healthVaultDataType = HealthVaultDataType .valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase()); } catch (NullPointerException | IllegalArgumentException e) { throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey() + " in shimDataRequest, cannot retrieve data."); } final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ss"); /*** * Setup default date parameters */ DateTime today = new DateTime(); DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1) : shimDataRequest.getStartDate(); String dateStart = startDate.toString(formatter); DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate(); String dateEnd = endDate.toString(formatter); long numToReturn = shimDataRequest.getNumToReturn() == null || shimDataRequest.getNumToReturn() <= 0 ? 100 : shimDataRequest.getNumToReturn(); Request request = new Request(); request.setMethodName("GetThings"); request.setInfo("<info>" + "<group max=\"" + numToReturn + "\">" + "<filter>" + "<type-id>" + healthVaultDataType.getDataTypeId() + "</type-id>" + "<eff-date-min>" + dateStart + "</eff-date-min>" + "<eff-date-max>" + dateEnd + "</eff-date-max>" + "</filter>" + "<format>" + "<section>core</section>" + "<xml/>" + "</format>" + "</group>" + "</info>"); RequestTemplate template = new RequestTemplate(connection); return template.makeRequest(shimDataRequest.getAccessParameters(), request, new Marshaller<ShimDataResponse>() { public ShimDataResponse marshal(InputStream istream) throws Exception { /** * XML Document mappings to JSON don't respect repeatable * tags, they don't get properly serialized into collections. * Thus, we pickup the 'things' via the 'group' root tag * and create a new JSON document out of each 'thing' node. */ XmlMapper xmlMapper = new XmlMapper(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(istream); NodeList nodeList = doc.getElementsByTagName("thing"); /** * Collect JsonNode from each 'thing' xml node. */ List<JsonNode> thingList = new ArrayList<>(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); Document thingDoc = builder.newDocument(); Node newNode = thingDoc.importNode(node, true); thingDoc.appendChild(newNode); thingList.add(xmlMapper.readTree(convertDocumentToString(thingDoc))); } /** * Rebuild JSON document structure to pass to deserializer. */ String thingsJson = "{\"things\":["; String thingsContent = ""; for (JsonNode thingNode : thingList) { thingsContent += thingNode.toString() + ","; } thingsContent = "".equals(thingsContent) ? thingsContent : thingsContent.substring(0, thingsContent.length() - 1); thingsJson += thingsContent; thingsJson += "]}"; /** * Return raw re-built 'things' or a normalized JSON document. */ ObjectMapper objectMapper = new ObjectMapper(); if (shimDataRequest.getNormalize()) { SimpleModule module = new SimpleModule(); module.addDeserializer(ShimDataResponse.class, healthVaultDataType.getNormalizer()); objectMapper.registerModule(module); return objectMapper.readValue(thingsJson, ShimDataResponse.class); } else { return ShimDataResponse.result(HealthvaultShim.SHIM_KEY, objectMapper.readTree(thingsJson)); } } }); }
From source file:org.apache.drill.exec.store.parquet.metadata.Metadata.java
/** * Read the parquet metadata from a file * * @param path to metadata file//from ww w . j a v a2 s . com * @param dirsOnly true for {@link Metadata#METADATA_DIRECTORIES_FILENAME} * or false for {@link Metadata#METADATA_FILENAME} files reading * @param metaContext current metadata context */ private void readBlockMeta(Path path, boolean dirsOnly, MetadataContext metaContext, FileSystem fs) { Stopwatch timer = logger.isDebugEnabled() ? Stopwatch.createStarted() : null; Path metadataParentDir = Path.getPathWithoutSchemeAndAuthority(path.getParent()); String metadataParentDirPath = metadataParentDir.toUri().getPath(); ObjectMapper mapper = new ObjectMapper(); final SimpleModule serialModule = new SimpleModule(); serialModule.addDeserializer(SchemaPath.class, new SchemaPath.De()); serialModule.addKeyDeserializer(Metadata_V2.ColumnTypeMetadata_v2.Key.class, new Metadata_V2.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); try (FSDataInputStream is = fs.open(path)) { boolean alreadyCheckedModification; boolean newMetadata = false; alreadyCheckedModification = metaContext.getStatus(metadataParentDirPath); if (dirsOnly) { parquetTableMetadataDirs = mapper.readValue(is, ParquetTableMetadataDirs.class); if (timer != null) { logger.debug("Took {} ms to read directories from directory cache file", timer.elapsed(TimeUnit.MILLISECONDS)); timer.stop(); } parquetTableMetadataDirs.updateRelativePaths(metadataParentDirPath); if (!alreadyCheckedModification && tableModified(parquetTableMetadataDirs.getDirectories(), path, metadataParentDir, metaContext, fs)) { parquetTableMetadataDirs = (createMetaFilesRecursively( Path.getPathWithoutSchemeAndAuthority(path.getParent()).toString(), fs)).getRight(); newMetadata = true; } } else { parquetTableMetadata = mapper.readValue(is, ParquetTableMetadataBase.class); if (timer != null) { logger.debug("Took {} ms to read metadata from cache file", timer.elapsed(TimeUnit.MILLISECONDS)); timer.stop(); } if (new MetadataVersion(parquetTableMetadata.getMetadataVersion()) .compareTo(new MetadataVersion(3, 0)) >= 0) { ((ParquetTableMetadata_v3) parquetTableMetadata).updateRelativePaths(metadataParentDirPath); } if (!alreadyCheckedModification && tableModified(parquetTableMetadata.getDirectories(), path, metadataParentDir, metaContext, fs)) { parquetTableMetadata = (createMetaFilesRecursively( Path.getPathWithoutSchemeAndAuthority(path.getParent()).toString(), fs)).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) { // if new metadata files were created, invalidate the existing metadata context metaContext.clear(); } } catch (IOException e) { logger.error("Failed to read '{}' metadata file", path, e); metaContext.setMetadataCacheCorrupted(true); } }
From source file:org.springside.examples.showcase.demos.utilities.json.JsonDemo.java
/** * ????MoneyLong.//from www . ja v a2s .c om */ @Test public void customConverter() { JsonMapper newMapper = JsonMapper.nonEmptyMapper(); SimpleModule moneyModule = new SimpleModule("MoneyModule"); moneyModule.addSerializer(new MoneySerializer()); moneyModule.addDeserializer(Money.class, new MoneyDeserializer()); newMapper.getMapper().registerModule(moneyModule); // tojson User user = new User(); user.setName("foo"); user.setSalary(new Money(1.2)); String jsonString = newMapper.toJson(user); assertThat(jsonString).isEqualTo("{\"name\":\"foo\",\"salary\":\"1.2\"}"); // from User resultUser = newMapper.fromJson(jsonString, User.class); assertThat(resultUser.getSalary().value).isEqualTo(1.2); }