@Before public void setUp() { SimpleModule module = new SimpleModule(); module.addSerializer(AnInterface.class, new AnInterfaceSerializer()); module.addDeserializer(AnInterface.class, new AnInterfaceDeserializer()); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false); mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false); mapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false); mapper.setVisibilityChecker(mapper.getSerializationConfig() .getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY)); Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(JacksonConverterFactory.create(mapper)) .build(); service = retrofit.create(Service.class); }
private static void initClient() { JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(); ObjectMapper objectMapper = JSONUtil.prettyMapper(); objectMapper.registerModule( new SimpleModule() .addDeserializer(JobDataFragment.class, new JsonDeserializer<JobDataFragment>() { @Override public JobDataFragment deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { return jsonParser.readValueAs(DataPOJO.class); } } ) ); provider.setMapper(objectMapper); client = ClientBuilder.newBuilder().register(provider).register(MultiPartFeature.class).build(); WebTarget rootTarget = client.target("http://localhost:" + currentDremioDaemon.getWebServer().getPort()); currentApiV2 = rootTarget.path(API_LOCATION); }
@JsonIgnore public List<AppStatus> getAppStatusList() { try { ObjectMapper mapper = new ObjectMapper(); mapper.addMixIn(AppStatus.class, AppStatusMixin.class); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); SimpleModule module = new SimpleModule("CustomModel", Version.unknownVersion()); SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver(); resolver.addMapping(AppInstanceStatus.class, AppInstanceStatusImpl.class); module.setAbstractTypes(resolver); mapper.registerModule(module); TypeReference<List<AppStatus>> typeRef = new TypeReference<List<AppStatus>>() { }; if (this.platformStatus != null) { return mapper.readValue(this.platformStatus, typeRef); } return new ArrayList<AppStatus>(); } catch (Exception e) { throw new IllegalArgumentException("Could not parse Skipper Platfrom Status JSON:" + platformStatus, e); } }
public static SecurityAnalysisResult read(Path jsonFile) { Objects.requireNonNull(jsonFile); try (InputStream is = Files.newInputStream(jsonFile)) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); SimpleModule module = new SimpleModule(); module.addDeserializer(SecurityAnalysisResult.class, new SecurityAnalysisResultDeserializer()); module.addDeserializer(NetworkMetadata.class, new NetworkMetadataDeserializer()); module.addDeserializer(PostContingencyResult.class, new PostContingencyResultDeserializer()); module.addDeserializer(LimitViolationsResult.class, new LimitViolationResultDeserializer()); module.addDeserializer(LimitViolation.class, new LimitViolationDeserializer()); module.addDeserializer(Contingency.class, new ContingencyDeserializer()); module.addDeserializer(ContingencyElement.class, new ContingencyElementDeserializer()); objectMapper.registerModule(module); return objectMapper.readValue(is, SecurityAnalysisResult.class); } catch (IOException e) { throw new UncheckedIOException(e); } }
public static void write(SecurityAnalysisResult result, Writer writer) throws IOException { Objects.requireNonNull(result); Objects.requireNonNull(writer); ObjectMapper objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(SecurityAnalysisResult.class, new SecurityAnalysisResultSerializer()); module.addSerializer(NetworkMetadata.class, new NetworkMetadataSerializer()); module.addSerializer(PostContingencyResult.class, new PostContingencyResultSerializer()); module.addSerializer(LimitViolationsResult.class, new LimitViolationsResultSerializer()); module.addSerializer(LimitViolation.class, new LimitViolationSerializer()); module.addSerializer(ContingencyElement.class, new ContingencyElementSerializer()); objectMapper.registerModule(module); ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter(); objectWriter.writeValue(writer, result); }
private static void write(Contingency object, Path jsonFile) { Objects.requireNonNull(object); Objects.requireNonNull(jsonFile); try (OutputStream os = Files.newOutputStream(jsonFile)) { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(ContingencyElement.class, new ContingencyElementSerializer()); mapper.registerModule(module); ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter(); writer.writeValue(os, object); } catch (IOException e) { throw new UncheckedIOException(e); } }
/** * Creates Crnk Jackson module with all required serializers.<br /> * Adds the {@link LinksInformationSerializer} if <code>serializeLinksAsObjects</code> is set to <code>true</code>. * * @param serializeLinksAsObjects flag which decides whether the {@link LinksInformationSerializer} should be added as * additional serializer or not. * * @return {@link com.fasterxml.jackson.databind.Module} with custom serializers */ public static SimpleModule createJacksonModule(boolean serializeLinksAsObjects) { SimpleModule simpleModule = new SimpleModule(JSON_API_JACKSON_MODULE_NAME, new Version(1, 0, 0, null, null, null)); simpleModule.addSerializer(new ErrorDataSerializer()); simpleModule.addDeserializer(ErrorData.class, new ErrorDataDeserializer()); if (serializeLinksAsObjects) { simpleModule.addSerializer(new LinksInformationSerializer()); } return simpleModule; }
public static ObjectMapper createDefaultMapper() { final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); mapper.configure(SerializationFeature.INDENT_OUTPUT, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); SimpleModule module = new SimpleModule(); module.addSerializer(Transaction.class, new TransactionSerializer()); module.addDeserializer(Transaction.class, new TransactionDeserializer()); module.addSerializer(Difficulty.class, new DifficultySerializer()); module.addDeserializer(Difficulty.class, new DifficultyDeserializer()); module.addSerializer(Block.class, new BlockSerializer()); module.addDeserializer(Block.class, new BlockDeserializer()); mapper.registerModule(module); return mapper; }
private ObjectExpression getEditorOptions(HtmlEditorConfiguration config) { final String options = config.getEditorOptions(); if( options == null || options.trim().length() == 0 ) { return null; } try { final ObjectMapper jsonMapper = objectMapperService.createObjectMapper(LenientMapperExtension.NAME); final SimpleModule module = new SimpleModule("equella", new Version(1, 0, 0, null)); module.addDeserializer(ObjectExpression.class, new ObjectExpressionDeserialiser()); jsonMapper.registerModule(module); final ObjectExpression obj = jsonMapper.readValue(options, ObjectExpression.class); return obj; // NOSONAR (kept local variable for readability) } catch( IOException io ) { // Invalid editor options. Should never have happened. LOGGER.error("Invalid HTML editor options", io); return null; } }
@Override public void extendMapper(ObjectMapper mapper) { SimpleModule restModule = new SimpleModule("RestModule", new Version(1, 0, 0, null)); // TODO this probably should be somewhere else, but it can't be in // com.tle.core.jackson // as that would make it dependent on equella i18n restModule.addSerializer(new I18NSerializer()); mapper.registerModule(restModule); mapper.registerModule(new JavaTypesModule()); mapper.registerModule(new RestStringsModule()); mapper.setSerializationInclusion(Include.NON_NULL); // dev mode! if( DebugSettings.isDebuggingMode() ) { mapper.configure(SerializationFeature.INDENT_OUTPUT, true); } mapper.setDateFormat(new ISO8061DateFormatWithTZ()); }
public BittrexExchange(int retries, String apikey, String secret, HttpFactory httpFactory) throws IOException { this.apikey = apikey; this.secret = secret; this.httpFactory = httpFactory; this.retries = retries; mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addDeserializer(ZonedDateTime.class, new DateTimeDeserializer()); mapper.registerModule(module); updateExchangeStateType = mapper.getTypeFactory().constructType(UpdateExchangeState.class); exchangeSummaryStateType = mapper.getTypeFactory().constructType(ExchangeSummaryState.class); httpClient = httpFactory.createClient(); httpClientContext = httpFactory.createClientContext(); }
public PhysicalPlanReader(DrillConfig config, ObjectMapper mapper, final DrillbitEndpoint endpoint, final StoragePluginRegistry pluginRegistry) { // Endpoint serializer/deserializer. SimpleModule deserModule = new SimpleModule("PhysicalOperatorModule") // .addSerializer(DrillbitEndpoint.class, new DrillbitEndpointSerDe.Se()) // .addDeserializer(DrillbitEndpoint.class, new DrillbitEndpointSerDe.De()) // .addSerializer(MajorType.class, new MajorTypeSerDe.Se()) .addDeserializer(MajorType.class, new MajorTypeSerDe.De()); mapper.registerModule(deserModule); mapper.registerSubtypes(PhysicalOperatorUtil.getSubTypes(config)); InjectableValues injectables = new InjectableValues.Std() // .addValue(StoragePluginRegistry.class, pluginRegistry) // .addValue(DrillbitEndpoint.class, endpoint); // this.mapper = mapper; this.physicalPlanReader = mapper.reader(PhysicalPlan.class).with(injectables); this.operatorReader = mapper.reader(PhysicalOperator.class).with(injectables); this.logicalPlanReader = mapper.reader(LogicalPlan.class).with(injectables); }
/** * 通过过滤器将对象转换成json * @param serializer * @param obj * @return * String * @Author chenxiaojin * @date 2014年11月25日 * @exception * @version */ public static JsonNode obj2NodeByFilter(FilterPropsSerializer filterSerializer, Object obj) { ObjectMapper objMapper = new ObjectMapper(); SimpleModule simpleModule = new SimpleModule(); // 添加需要过滤的Class for (Class<?> clz : filterSerializer.getSerializerClasses()) { simpleModule.addSerializer(clz, filterSerializer); } // 注册模块 objMapper.registerModule(simpleModule); objMapper.setDateFormat(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")); try { String result = objMapper.writeValueAsString(obj); return objMapper.readTree(result); } catch (IOException e) { return null; } }
@Test public void customDecoder() throws Exception { JacksonDecoder decoder = new JacksonDecoder( Arrays.<Module>asList( new SimpleModule().addDeserializer(Zone.class, new ZoneDeserializer()))); List<Zone> zones = new LinkedList<Zone>(); zones.add(new Zone("DENOMINATOR.IO.")); zones.add(new Zone("DENOMINATOR.IO.", "ABCD")); Response response = Response.builder() .status(200) .reason("OK") .headers(Collections.<String, Collection<String>>emptyMap()) .body(zonesJson, UTF_8) .build(); assertEquals(zones, decoder.decode(response, new TypeReference<List<Zone>>() { }.getType())); }
@Test public void customEncoder() throws Exception { JacksonEncoder encoder = new JacksonEncoder( Arrays.<Module>asList(new SimpleModule().addSerializer(Zone.class, new ZoneSerializer()))); List<Zone> zones = new LinkedList<Zone>(); zones.add(new Zone("denominator.io.")); zones.add(new Zone("denominator.io.", "abcd")); RequestTemplate template = new RequestTemplate(); encoder.encode(zones, new TypeReference<List<Zone>>() { }.getType(), template); assertThat(template).hasBody("" // + "[ {\n" + " \"name\" : \"DENOMINATOR.IO.\"\n" + "}, {\n" + " \"name\" : \"DENOMINATOR.IO.\",\n" + " \"id\" : \"ABCD\"\n" + "} ]"); }
public VPackMapper() { super(new VPackFactory()); configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); final SimpleModule module = new SimpleModule(); module.addSerializer(java.util.Date.class, VPackSerializers.UTIL_DATE); module.addSerializer(java.sql.Date.class, VPackSerializers.SQL_DATE); module.addSerializer(java.sql.Timestamp.class, VPackSerializers.SQL_TIMESTAMP); module.addDeserializer(java.util.Date.class, VPackDeserializers.UTIL_DATE); module.addDeserializer(java.sql.Date.class, VPackDeserializers.SQL_DATE); module.addDeserializer(java.sql.Timestamp.class, VPackDeserializers.SQL_TIMESTAMP); // module.addKeySerializer(Boolean.class, VPackKeySerializers.BOOLEAN); // module.addKeySerializer(Integer.class, VPackKeySerializers.INTEGER); // module.addKeySerializer(Long.class, VPackKeySerializers.LONG); // module.addKeySerializer(Short.class, VPackKeySerializers.SHORT); // module.addKeySerializer(Double.class, VPackKeySerializers.DOUBLE); // module.addKeySerializer(Float.class, VPackKeySerializers.FLOAT); // module.addKeySerializer(Character.class, VPackKeySerializers.CHARACTER); // module.addKeyDeserializer(Boolean.class, StdKeyDeserializer.forType(Boolean.class)); // module.addKeyDeserializer(Integer.class, StdKeyDeserializer.forType(Integer.class)); // module.addKeyDeserializer(Long.class, StdKeyDeserializer.forType(Long.class)); // module.addKeyDeserializer(Short.class, StdKeyDeserializer.forType(Short.class)); // module.addKeyDeserializer(Double.class, StdKeyDeserializer.forType(Double.class)); // module.addKeyDeserializer(Float.class, StdKeyDeserializer.forType(Float.class)); // module.addKeyDeserializer(Character.class, StdKeyDeserializer.forType(Character.class)); registerModule(module); }
public String getSaveString() { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); //The custom serializer being added to the module module.addSerializer(SaveFile.class, new SaveSerializer()); mapper.registerModule(module); try { //The seriealized game object, where we defined the things we want serialized in the custom serializer, gets serialized into Savestring. Savestring = mapper.writeValueAsString(this); } catch (JsonProcessingException ex) { Logger.getLogger(SaveFile.class.getName()).log(Level.SEVERE, null, ex); } return Savestring; }
/** * method that uses a Jackson mapper to read a json file and tun it into an arraylist of IPersonalScore objects * @return an arraylist of IPersonalScore objects. */ ArrayList loadHighscore() { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("ScoreSerializer", new Version(1, 0, 0, null, null, null)); module.addDeserializer(DataPS.class, new ScoreDeserializer()); mapper.registerModule(module); try { scoreList = mapper.readValue(new File("files/highscore.json"), new TypeReference<ArrayList<DataPS>>(){}); } catch (IOException ex) { Logger.getLogger(DataHighscore.class.getName()).log(Level.SEVERE, null, ex); } return scoreList; }
protected AbstractZg2proRestTemplate(SimpleModule sm) { super(); //converters List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(new ByteArrayHttpMessageConverter()); messageConverters.add(new ResourceHttpMessageConverter()); ObjectMapper jsonMapper = camelToKebabObjectMapper(sm); messageConverters.add(new MappingJackson2HttpMessageConverter(jsonMapper)); this.setMessageConverters(messageConverters); //errors handling setErrorHandler(new RestTemplateErrorHandler()); /* //interceptors LoggingRequestInterceptor lri = new LoggingRequestInterceptor(); this.setInterceptors(new ArrayList<>()); this.getInterceptors().add(lri); this.setRequestFactory(LoggingRequestFactoryFactory.build(lri)); */ }
@Override public void configure(Map configs, boolean isKey) { String documentBasePackage = (String) configs.get("documentBasePackage"); SimpleModule module = new SimpleModule(); Set<Class<?>> annotatedClasses = ClassUtils.getAnnotatedClasses(documentBasePackage, Document.class); annotatedClasses.forEach(aClass -> module.addSerializer(aClass, new MetaableJkesJsonSerializer<>())); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); // mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // Feature is enabled by default, so that date/time are by default serialized as timestamps. mapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES); this.mapper = mapper; }
@Activate public void activate() { mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(NodeId.class, new NodeIdSerializer()); module.addDeserializer(NodeId.class, new NodeIdDeserializer()); module.addSerializer(ControllerNode.class, new ControllerNodeSerializer()); module.addDeserializer(ControllerNode.class, new ControllerNodeDeserializer()); module.addDeserializer(Partition.class, new PartitionDeserializer()); module.addSerializer(PartitionId.class, new PartitionIdSerializer()); module.addDeserializer(PartitionId.class, new PartitionIdDeserializer()); mapper.registerModule(module); providerService = providerRegistry.register(this); metadataUrl = System.getProperty("onos.cluster.metadata.uri", "file://" + CONFIG_DIR + "/" + CONFIG_FILE); configFileChangeDetector.scheduleWithFixedDelay(() -> watchUrl(metadataUrl), 100, 500, TimeUnit.MILLISECONDS); log.info("Started"); }
@Override public void generate(Object obj, OutputStream os, boolean prettyPrint) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.CLOSE_CLOSEABLE, false); mapper.configure(SerializationFeature.FLUSH_AFTER_WRITE_VALUE, false); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); if (prettyPrint) { mapper.enable(SerializationFeature.INDENT_OUTPUT); } SimpleModule module = new SimpleModule(); module.addSerializer(CfnObject.class, new CfnObjectSerializer(resourceSpecificationService)); module.addSerializer(IntrinsicFunction.class, new IntrinsicFunctionSerializer()); mapper.registerModule(module); try { mapper.writeValue(os, obj); os.flush(); } catch (IOException e) { throw new RuntimeException(e); } }
/** * 获取ObjectMapper反序列化枚举使用的module * 支持忽略大小写 * @return */ public static SimpleModule getEnumSimpleModule() { //枚举转换,支持忽略大小写的匹配 SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override 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 rawClass = type.getRawClass(); return getEnum(jp.getValueAsString(), rawClass); } }; } }); return module; }
public static ObjectMapper create(ObjectMapper original, CustomComparators customComparators) { ObjectMapper mapper = original.copy() .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true) .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); /* * Get the original instance of the SerializerProvider before we add our custom module. * Our Collection Delegating code does not call itself. */ SerializerProvider serializers = mapper.getSerializerProviderInstance(); // This module is reponsible for replacing non-deterministic objects // with deterministic ones. Example convert Set to a sorted List. SimpleModule module = new SimpleModule(); module.addSerializer(Collection.class, new CustomDelegatingSerializerProvider(serializers, new CollectionToSortedListConverter(customComparators)) ); mapper.registerModule(module); return mapper; }
public LogicalPlanPersistence(SabotConfig conf, ScanResult scanResult) { mapper = new ObjectMapper(); SimpleModule deserModule = new SimpleModule("LogicalExpressionDeserializationModule") .addDeserializer(LogicalExpression.class, new LogicalExpression.De(conf)) .addDeserializer(SchemaPath.class, new SchemaPath.De()); mapper.registerModule(new AfterburnerModule()); mapper.registerModule(deserModule); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true); mapper.configure(Feature.ALLOW_COMMENTS, true); registerSubtypes(LogicalOperatorBase.getSubTypes(scanResult)); registerSubtypes(StoragePluginConfigBase.getSubTypes(scanResult)); registerSubtypes(FormatPluginConfigBase.getSubTypes(scanResult)); }
private static <T1, T2> SimpleModule newWrappingModule(final Class<T1> wrapped, final Class<T2> wrapper, final Converter<T1, T2> converter) { SimpleModule module = new SimpleModule(); module.addDeserializer(wrapper, new JsonDeserializer<T2>() { @Override public T2 deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { return converter.convert(ctxt.readValue(p, wrapped)); } }); module.addSerializer(wrapper, new JsonSerializer<T2>() { @Override public void serialize(T2 value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { serializers.defaultSerializeValue(converter.revert(value), gen); } }); return module; }
private static void initMasterClient() { JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(); ObjectMapper objectMapper = JSONUtil.prettyMapper(); objectMapper.registerModule( new SimpleModule() .addDeserializer(JobDataFragment.class, new JsonDeserializer<JobDataFragment>() { @Override public JobDataFragment deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { return jsonParser.readValueAs(DataPOJO.class); } } ) ); provider.setMapper(objectMapper); masterClient = ClientBuilder.newBuilder().register(provider).register(MultiPartFeature.class).build(); WebTarget rootTarget = masterClient.target("http://localhost:" + masterDremioDaemon.getWebServer().getPort()); masterApiV2 = rootTarget.path(API_LOCATION); }
/** * Creates a new EclipseParser * * @param sourceFile String of source file to read * @param outJ JSON parsed out * @throws IOException when file can't be opened or errors in reading/writing */ public EclipseParser(String sourceFile, PrintStream outJ, boolean prettyprint) throws IOException { File file = new File(sourceFile); final BufferedReader reader = new BufferedReader(new FileReader(file)); char[] source = IOUtils.toCharArray(reader); reader.close(); this.parser = ASTParser.newParser(AST.JLS8); parser.setSource(source); parser.setKind(ASTParser.K_COMPILATION_UNIT); final JsonFactory jsonF = new JsonFactory(); jG = jsonF.createGenerator(outJ); if (prettyprint) { jG.setPrettyPrinter(new DefaultPrettyPrinter()); mapper.enable(SerializationFeature.INDENT_OUTPUT); } mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); SimpleModule module = new SimpleModule(); module.addSerializer(ASTNode.class, new NodeSerializer()); mapper.registerModule(module); }
/** * Generates an {@link ObjectMapper} to serialize and deserialize JSON. * * @return The generated {@link ObjectMapper}. */ @Bean public ObjectMapper getDefaultObjectMapper() { final ObjectMapper mapper = new ObjectMapper(); final SimpleModule module = new SimpleModule("AnalysisSerializers", new Version(1, 0, 0, null, null, null)); // Add custom serializer & deserializer for AnalyzerType so that we can retrieve the correct singleton instance from spring module.addSerializer(AnalyzerType.class, new AnalyzerTypeSerializer()); module.addDeserializer(AnalyzerType.class, new AnalyzerTypeDeserializer()); // Add custom serializer & deserializer for Analyzer so that we can save the parameter values used to create the analyzer module.addSerializer(Analyzer.class, new AnalyzerSerializer()); module.addDeserializer(Analyzer.class, new AnalyzerDeserializer()); mapper.registerModule(module); // Save type information in JSON when declared type is object so it is deserialized correctly // Used because AnalyzerSpec has a map of string to object for saved parameter values mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT); return mapper; }
/** * Create an instance of the API for authenticated access * @param username an OpenSky username * @param password an OpenSky password for the given username */ public OpenSkyApi(String username, String password) { lastRequestTime = new HashMap<>(); // set up JSON mapper mapper = new ObjectMapper(); SimpleModule sm = new SimpleModule(); sm.addDeserializer(OpenSkyStates.class, new OpenSkyStatesDeserializer()); mapper.registerModule(sm); authenticated = username != null && password != null; if (authenticated) { okHttpClient = new OkHttpClient.Builder() .addInterceptor(new BasicAuthInterceptor(username, password)) .build(); } else { okHttpClient = new OkHttpClient(); } }
public LogicalPlanPersistence(DrillConfig conf, ScanResult scanResult) { mapper = new ObjectMapper(); SimpleModule deserModule = new SimpleModule("LogicalExpressionDeserializationModule") .addDeserializer(LogicalExpression.class, new LogicalExpression.De(conf)) .addDeserializer(SchemaPath.class, new SchemaPath.De()); mapper.registerModule(deserModule); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true); mapper.configure(Feature.ALLOW_COMMENTS, true); registerSubtypes(LogicalOperatorBase.getSubTypes(scanResult)); registerSubtypes(StoragePluginConfigBase.getSubTypes(scanResult)); registerSubtypes(FormatPluginConfigBase.getSubTypes(scanResult)); }
public ObjectMapper getObjectMapper(){ if(mapper==null){ mapper=new ObjectMapper(); mapper.configure(MapperFeature.USE_ANNOTATIONS, true); mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); mapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, true); mapper.configure(JsonParser.Feature.ALLOW_MISSING_VALUES, true); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setTimeZone(TimeZone.getDefault()); SimpleModule module = new SimpleModule(); module.addSerializer(DateTime.class,new DateTimeSerializer()); module.addDeserializer(DateTime.class,new DateTimeDeserializer()); mapper.registerModule(module); } return mapper; }
private ObjectMapper getDefaultObjectMapper(boolean xml, boolean details, TreeNode<String, Boolean> perms) { if (perms == null) { throw new NullPointerException("Permissions may not be null"); } ObjectMapper om = xml ? new XmlMapper() : new ObjectMapper(); om.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleModule mod = new SimpleModule(); for (Map.Entry<Class, BaseSerializer> entry : serializers.entrySet()) { mod.addSerializer(entry.getKey(), entry.getValue()); } mod.addDeserializer(ItemStack.class, new ItemStackDeserializer()); mod.addDeserializer(BlockState.class, new BlockStateDeserializer()); mod.addDeserializer(ItemStackSnapshot.class, new ItemStackSnapshotDeserializer()); mod.addDeserializer(Location.class, new LocationDeserializer()); om.registerModule(mod); SimpleFilterProvider filterProvider = new SimpleFilterProvider(); filterProvider.addFilter(BaseFilter.ID, new BaseFilter(details, perms)); om.setFilterProvider(filterProvider); om.setAnnotationIntrospector(new AnnotationIntrospector(details)); return om; }
@Provides @Singleton ObjectMapper provideObjectMapper() { SimpleModule module = new SimpleModule(); module.setSerializerModifier(new MentorSerializerModifier()); return new ObjectMapper() .configure(SerializationFeature.WRAP_ROOT_VALUE, false) .configure(SerializationFeature.INDENT_OUTPUT, false) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true) .disable(MapperFeature.AUTO_DETECT_CREATORS) .disable(MapperFeature.AUTO_DETECT_FIELDS) .disable(MapperFeature.AUTO_DETECT_GETTERS) .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) .setSerializationInclusion(Include.NON_NULL) .setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")) .registerModule(module) ; }
public JacksonObjectMapperConfig() { super(); this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); //this.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); 不增加,避免key值为null,而避免节点消失 this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); this.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); //this.setSerializationInclusion(Include.NON_EMPTY); //对象转字符串时,只转化非空字段 zjs 需要占位 //SimpleModule module = new SimpleModule(); SimpleModule module = new SimpleModule("HTML XSS Serializer", new Version(1, 0, 0, "FINAL", "com.simbest", "ep-jsonmodule")); module.addSerializer(new JsonHtmlXssSerializer(String.class)); module.addDeserializer(Date.class, new CustomJsonDateDeseralizer()); // Add more here ... registerModule(module); }
private void testWDTKParsing(String filename) throws IOException { String jsonString = readFile(filename, StandardCharsets.UTF_8); SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new MapDeserializerModifier()); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); // JsonNode root = mapper.readTree(jsonString); // mapper.readValue(mapper.treeAsTokens(root), JacksonItemDocument.class); JacksonItemDocument itemDocument = mapper.readValue(jsonString, JacksonItemDocument.class); itemDocument.setSiteIri(Datamodel.SITE_WIKIDATA); itemDocument.toString(); // raises an exception if information is missing }
protected AbstractAwsIotDevice(String thingName) { this.thingName = thingName; reportedProperties = getDeviceProperties(true, false); updatableProperties = getDeviceProperties(false, true); commandManager = new AwsIotDeviceCommandManager(this); deviceSubscriptions = new ConcurrentHashMap<>(); for (String topic : getDeviceTopics()) { deviceSubscriptions.put(topic, false); } jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(AbstractAwsIotDevice.class, new AwsIotJsonSerializer()); jsonObjectMapper.registerModule(module); localVersion = new AtomicLong(-1); }
@Test public void test1() { InstanceData_old data = InstanceDataGenerator_old.build(); System.out.println(data.toString()); try { ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module()); SimpleModule module = new SimpleModule(); module.addKeyDeserializer(TypeVMJobClassKey.class, TypeVMJobClassKey.getDeserializer() ); mapper.registerModule(module); String serialized = mapper.writeValueAsString(data); System.out.println(serialized); InstanceData_old data2 = mapper.readValue(serialized, InstanceData_old.class); System.out.println(data2.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertTrue(data.getGamma() ==240); }
@Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.setDeserializerModifier( new BeanDeserializerModifier() { @Override 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.addDeserializer( Expression.class, new ExpressionDeserializer( expressionParser() ) ); module.addDeserializer( Range.class, new RangeDeserializer() ); mapper.registerModule( module ); return mapper; }