@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); }
@Test public void defaultObjectMapperBuilder() throws Exception { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); Jackson2ObjectMapperBuilder builder = this.context .getBean(Jackson2ObjectMapperBuilder.class); ObjectMapper mapper = builder.build(); assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue(); assertThat(mapper.getDeserializationConfig() .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue(); assertThat(mapper.getDeserializationConfig() .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); assertThat(mapper.getSerializationConfig() .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()) .isTrue(); assertThat(mapper.getDeserializationConfig() .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); }
@Test public void additionalPropertiesWorkWithAllVisibility() throws ClassNotFoundException, SecurityException, NoSuchMethodException, JsonProcessingException, IOException { mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false); mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false); mapper.setVisibility(mapper.getVisibilityChecker().with(Visibility.ANY)); ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/additionalProperties/defaultAdditionalProperties.json", "com.example"); Class<?> classWithAdditionalProperties = resultsClassLoader.loadClass("com.example.DefaultAdditionalProperties"); String jsonWithAdditionalProperties = "{\"a\":1, \"b\":2};"; Object instanceWithAdditionalProperties = mapper.readValue(jsonWithAdditionalProperties, classWithAdditionalProperties); JsonNode jsonNode = mapper.readTree(mapper.writeValueAsString(instanceWithAdditionalProperties)); assertThat(jsonNode.path("a").asText(), is("1")); assertThat(jsonNode.path("b").asInt(), is(2)); assertThat(jsonNode.has("additionalProperties"), is(false)); }
public static ObjectMapper objectMapper() { return new ObjectMapper() // Property visibility .setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS) .setDefaultVisibility(JsonAutoDetect.Value.construct(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC)) .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true) // Property naming and order .setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE) // Customised de/serializers // Formats, locals, encoding, binary data .setDateFormat(new SimpleDateFormat("MM/dd/yyyy")) .setDefaultPrettyPrinter(new DefaultPrettyPrinter()) .setLocale(Locale.CANADA); }
public static GenesisJson loadGenesisJson(InputStream genesisJsonIS) throws RuntimeException { String json = null; try { json = new String(ByteStreams.toByteArray(genesisJsonIS)); ObjectMapper mapper = new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); GenesisJson genesisJson = mapper.readValue(json, GenesisJson.class); return genesisJson; } catch (Exception e) { Utils.showErrorAndExit("Problem parsing genesis: "+ e.getMessage(), json); throw new RuntimeException(e.getMessage(), e); } }
private void configureFeature(Object feature, boolean enabled) { if (feature instanceof JsonParser.Feature) { this.objectMapper.configure((JsonParser.Feature) feature, enabled); } else if (feature instanceof JsonGenerator.Feature) { this.objectMapper.configure((JsonGenerator.Feature) feature, enabled); } else if (feature instanceof SerializationFeature) { this.objectMapper.configure((SerializationFeature) feature, enabled); } else if (feature instanceof DeserializationFeature) { this.objectMapper.configure((DeserializationFeature) feature, enabled); } else if (feature instanceof MapperFeature) { this.objectMapper.configure((MapperFeature) feature, enabled); } else { throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName()); } }
public EsInstanceStore(String host, int port) { super(host, port); //This is required to let ES create the mapping of Date instead of long insertMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); updateMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .addMixIn(getInstanceClass(), IgnoreCreatedTimeMixin.class); //Specific mapper to read EsDailySnapshotInstance from the index essnapshotinstanceMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .setPropertyNamingStrategy(new EsPropertyNamingStrategy( EsDailySnapshotInstance.class, EsInstanceStore.class)) .configure(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING, true); }
@Test public void deserializeWithStrategy() throws Exception { ObjectMapper mapper = new ObjectMapper().configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .setPropertyNamingStrategy(new EsPropertyNamingStrategy( EsDailySnapshotInstance.class, EsInstanceStore.class)) .configure(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING, true); EsDailySnapshotInstance inst = mapper.readValue(doc, EsDailySnapshotInstance.class); Assert.assertEquals("coreapp-webapp-prod-0a018ef5", inst.getName()); Assert.assertEquals("fixed", inst.getLifecycle()); Assert.assertTrue(inst.getLaunchTime() != null); }
private void configureerMapper() { // Configuratie this.disable(MapperFeature.AUTO_DETECT_CREATORS); this.disable(MapperFeature.AUTO_DETECT_FIELDS); this.disable(MapperFeature.AUTO_DETECT_GETTERS); this.disable(MapperFeature.AUTO_DETECT_IS_GETTERS); this.disable(MapperFeature.AUTO_DETECT_SETTERS); // Default velden niet als JSON exposen (expliciet annoteren!) setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.NONE); this.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); this.enable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS); // serialization this.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); setSerializationInclusion(JsonInclude.Include.NON_EMPTY); this.enable(SerializationFeature.WRITE_ENUMS_USING_INDEX); // deserialization this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); }
private static ObjectMapper initializeMapper() { return new ObjectMapper() .registerModule(new JavaTimeModule()) .disable(MapperFeature.AUTO_DETECT_GETTERS) .disable(MapperFeature.AUTO_DETECT_CREATORS) .disable(MapperFeature.AUTO_DETECT_SETTERS) .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) .disable(MapperFeature.AUTO_DETECT_FIELDS) .disable(MapperFeature.DEFAULT_VIEW_INCLUSION) .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.NONE) .enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY) .enable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS) // serialization .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .enable(SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // deserialization .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE); }
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; }
@Before public void setup() throws IOException { mockWebServer = new MockWebServer(); mockWebServer.start(); ObjectMapper objectMapper = new ObjectMapper().disable( MapperFeature.AUTO_DETECT_CREATORS, MapperFeature.AUTO_DETECT_FIELDS, MapperFeature.AUTO_DETECT_GETTERS, MapperFeature.AUTO_DETECT_IS_GETTERS) .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); DeltaApi deltaApi = new Retrofit.Builder() .baseUrl(mockWebServer.url("").toString()) .addConverterFactory(JacksonConverterFactory.create(objectMapper)) .build() .create(DeltaApi.class); apiClient = new DeltaApiClient(deltaApi); }
public IndividualPokemonRepository(String file) throws Exception { String legacy = null; if (!file.equals(POKEMONGO_JSON)) { legacy = file.substring(0, 8); } final InputStream is = this.getClass().getResourceAsStream(file); if (is == null) { throw new IllegalArgumentException("Can not find " + file); } mapper = new ObjectMapper(); mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); printer = JsonFormat.printer().includingDefaultValueFields(); final RawData rawData = mapper.readValue(is, RawData.class); all = createPokemons(rawData, legacy); pokemonMap = all.getPokemonList().stream().collect(Collectors.toMap(p -> p.getPokemonId(), p -> p)); log.info("Loaded {} pokemons", all.getPokemonCount()); }
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) { if (feature instanceof JsonParser.Feature) { objectMapper.configure((JsonParser.Feature) feature, enabled); } else if (feature instanceof JsonGenerator.Feature) { objectMapper.configure((JsonGenerator.Feature) feature, enabled); } else if (feature instanceof SerializationFeature) { objectMapper.configure((SerializationFeature) feature, enabled); } else if (feature instanceof DeserializationFeature) { objectMapper.configure((DeserializationFeature) feature, enabled); } else if (feature instanceof MapperFeature) { objectMapper.configure((MapperFeature) feature, enabled); } else { throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName()); } }
@Test public void booleanSetters() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() .featuresToEnable(MapperFeature.DEFAULT_VIEW_INCLUSION, DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, SerializationFeature.INDENT_OUTPUT) .featuresToDisable(MapperFeature.AUTO_DETECT_FIELDS, MapperFeature.AUTO_DETECT_GETTERS, MapperFeature.AUTO_DETECT_SETTERS, SerializationFeature.FAIL_ON_EMPTY_BEANS).build(); assertNotNull(objectMapper); assertTrue(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertTrue(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS)); assertTrue(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)); assertFalse(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); }
@Test public void booleanSetters() { this.factory.setAutoDetectFields(false); this.factory.setAutoDetectGettersSetters(false); this.factory.setDefaultViewInclusion(false); this.factory.setFailOnEmptyBeans(false); this.factory.setIndentOutput(true); this.factory.afterPropertiesSet(); ObjectMapper objectMapper = this.factory.getObject(); assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS)); assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT)); assertSame(Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion()); }
@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) ; }
private static void configure(ObjectMapper om, Object feature, boolean state) { if (feature instanceof SerializationFeature) om.configure((SerializationFeature) feature, state); else if (feature instanceof DeserializationFeature) om.configure((DeserializationFeature) feature, state); else if (feature instanceof JsonParser.Feature) om.configure((JsonParser.Feature) feature, state); else if (feature instanceof JsonGenerator.Feature) om.configure((JsonGenerator.Feature) feature, state); else if (feature instanceof MapperFeature) om.configure((MapperFeature) feature, state); else if (feature instanceof Include) { if (state) { om.setSerializationInclusion((Include) feature); } } }
@Test public void shouldMarshalFunnyNames() throws IOException { FunnyNames funnyNames = new FunnyNames(); funnyNames.setCustomerName("Donald Duck"); funnyNames.setInterface(-1); funnyNames.setSomeOtherName("Voldemort"); funnyNames.setStatic(true); StringWriter sw = new StringWriter(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); mapper.writer().writeValue(sw, funnyNames); String json = sw.toString(); assertThat(json).isEqualTo("{\"customer.name\":\"Donald Duck\",\"interface\":-1,\"rawName\":\"Voldemort\",\"static\":true}"); }
@Test public void enableMapperFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.mapper.require_setters_for_getters:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()) .isFalse(); assertThat(mapper.getSerializationConfig() .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) .isTrue(); assertThat(mapper.getDeserializationConfig() .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) .isTrue(); }
public static byte[] convertObjectToJsonBytes( Object object ) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion( JsonInclude.Include.NON_NULL ); objectMapper.configure( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false ); objectMapper.configure( SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false ); objectMapper.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false ); objectMapper.configure( SerializationFeature.WRAP_EXCEPTIONS, true ); objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false ); objectMapper.configure( DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true ); objectMapper.configure( DeserializationFeature.WRAP_EXCEPTIONS, true ); objectMapper.disable( MapperFeature.AUTO_DETECT_FIELDS ); objectMapper.disable( MapperFeature.AUTO_DETECT_CREATORS ); objectMapper.disable( MapperFeature.AUTO_DETECT_GETTERS ); objectMapper.disable( MapperFeature.AUTO_DETECT_SETTERS ); objectMapper.disable( MapperFeature.AUTO_DETECT_IS_GETTERS ); return objectMapper.writeValueAsBytes( object ); }
public static void main(String[] args) throws IOException { CsvParam csvParam = new CsvParam(); csvParam.setUp(); CsvMapper csvMapper = new CsvMapper(); csvMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); CsvSchema bootstrapSchema = CsvSchema.emptySchema().withHeader(); try(Reader reader = csvParam.getReader()) { MappingIterator<City> iterator = csvMapper.readerFor(City.class).with(bootstrapSchema).readValues(reader); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
@Override public ConfigurationFactory get() { Map<String, String> vars = environment.frameworkVariables(); Map<String, String> properties = environment.frameworkProperties(); JsonNode rootNode = loadConfiguration(properties, vars); ObjectMapper jsonToObjectMapper = jacksonService.newObjectMapper(); if (!vars.isEmpty()) { // switching to slower CI strategy for mapping properties... jsonToObjectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); } return new JsonNodeConfigurationFactory(rootNode, jsonToObjectMapper); }
@Test public void defaultObjectMapperBuilder() throws Exception { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); Jackson2ObjectMapperBuilder builder = this.context .getBean(Jackson2ObjectMapperBuilder.class); ObjectMapper mapper = builder.build(); assertTrue(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()); assertFalse(mapper.getDeserializationConfig() .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertTrue(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()); assertFalse(mapper.getDeserializationConfig() .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertFalse(mapper.getSerializationConfig() .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertTrue(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()); assertFalse(mapper.getDeserializationConfig() .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); }
public static JsonNode createJsonNode(List<Tuple> objectsWithLinks, List<Link> links, Class clazz) throws JsonProcessingException { MAPPER.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); ArrayNode array = MAPPER.createArrayNode(); for(Tuple objectWithLink : objectsWithLinks) { ObjectNode node = (ObjectNode) Json.parse(MAPPER.writerWithView(Summary.class).writeValueAsString(objectWithLink.getObject())); if(objectWithLink.link != null) node.put(LINKS, addlinkToNode(MAPPER.createObjectNode(), objectWithLink.getLink())); array.add(node); } ObjectNode nodeWithArray = Json.newObject(); nodeWithArray.put(DEFAULT_ROOT_ELEMENT, array); MAPPER.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true); return createJsonNode(nodeWithArray, links, clazz); }
@Bean public ObjectMapper jsonObjectMapper() { final ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); jsonMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true); jsonMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); final SimpleModule module = new SimpleModule("FieldsMapping", Version.unknownVersion()); module.setSerializerModifier(new BeanSerializerModifier() { @Override public JsonSerializer<?> modifyMapSerializer(final SerializationConfig config, final MapType valueType, final BeanDescription beanDesc, final JsonSerializer<?> serializer) { if (FieldsMap.class.isAssignableFrom(valueType.getRawClass())) { return new FieldsMapMixInLikeSerializer(); } else { return super.modifyMapSerializer(config, valueType, beanDesc, serializer); } } }); jsonMapper.registerModule(module); return jsonMapper; }
@Test void shouldSerializeWithoutAutoDetect() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper() .disable(MapperFeature.AUTO_DETECT_FIELDS) .disable(MapperFeature.AUTO_DETECT_GETTERS) .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) .registerModule(new ProblemModule()) .registerModule(new ConstraintViolationProblemModule()); final Violation violation = new Violation("bob", "was missing"); final ConstraintViolationProblem unit = new ConstraintViolationProblem(BAD_REQUEST, singletonList(violation)); with(mapper.writeValueAsString(unit)) .assertThat("status", is(400)) .assertThat("type", is(ConstraintViolationProblem.TYPE_VALUE)) .assertThat("title", is("Constraint Violation")) .assertThat("violations", hasSize(1)) .assertThat("violations.*.field", contains("bob")) .assertThat("violations.*.message", contains("was missing")); }
@Autowired public StreamController(ClusterRegistry registry, Observable<Boolean> shutdown) { Objects.requireNonNull(registry); Objects.requireNonNull(shutdown); ObjectMapper om = new ObjectMapper(); om.enable(MapperFeature.AUTO_DETECT_FIELDS); om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); Observable<HystrixClusterMetrics> metricsObs = registry.observe(); streamObservable = metricsObs .takeUntil(shutdown) .map(d -> { try { return om.writeValueAsString(d); } catch (JsonProcessingException e) { throw new RuntimeException(e); } }) .share(); }
@Bean @Primary ObjectMapper objectMapper() { // HATEOAS disables the default Spring configuration options described at // https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper // See https://github.com/spring-projects/spring-hateoas/issues/333. // We fix this by applying the Spring configurator on the HATEOAS object mapper // See also // https://github.com/spring-projects/spring-boot/blob/v1.3.2.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java // which already seems to do this but does not work ObjectMapper springHateoasObjectMapper = beanFactory.getBean(SPRING_HATEOAS_OBJECT_MAPPER, ObjectMapper.class); Jackson2ObjectMapperBuilder builder = beanFactory.getBean(Jackson2ObjectMapperBuilder.class); builder.configure(springHateoasObjectMapper); // By default, Jackson converts dates to UTC. This causes issues when passing inactivity creation requests from the app // service to the analysis engine service. springHateoasObjectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); // This way, the JsonView annotations on the controlers work properly springHateoasObjectMapper.enable(MapperFeature.DEFAULT_VIEW_INCLUSION); return springHateoasObjectMapper; }
public JsonSerializer<?> createContextual(SerializerProvider paramSerializerProvider, BeanProperty paramBeanProperty) { JsonSerializer localJsonSerializer1 = this._valueSerializer; if (localJsonSerializer1 == null) { if ((paramSerializerProvider.isEnabled(MapperFeature.USE_STATIC_TYPING)) || (Modifier.isFinal(this._accessorMethod.getReturnType().getModifiers()))) { JavaType localJavaType = paramSerializerProvider.constructType(this._accessorMethod.getGenericReturnType()); JsonSerializer localJsonSerializer2 = paramSerializerProvider.findTypedValueSerializer(localJavaType, false, this._property); return withResolved(paramBeanProperty, localJsonSerializer2, isNaturalTypeWithStdHandling(localJavaType.getRawClass(), localJsonSerializer2)); } } else if ((localJsonSerializer1 instanceof ContextualSerializer)) return withResolved(paramBeanProperty, ((ContextualSerializer)localJsonSerializer1).createContextual(paramSerializerProvider, paramBeanProperty), this._forceTypeInformation); return this; }
protected void processViews(SerializationConfig paramSerializationConfig, BeanSerializerBuilder paramBeanSerializerBuilder) { List localList = paramBeanSerializerBuilder.getProperties(); boolean bool = paramSerializationConfig.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION); int i = localList.size(); int j = 0; BeanPropertyWriter[] arrayOfBeanPropertyWriter = new BeanPropertyWriter[i]; for (int k = 0; k < i; k++) { BeanPropertyWriter localBeanPropertyWriter = (BeanPropertyWriter)localList.get(k); Class[] arrayOfClass = localBeanPropertyWriter.getViews(); if (arrayOfClass == null) { if (bool) arrayOfBeanPropertyWriter[k] = localBeanPropertyWriter; } else { j++; arrayOfBeanPropertyWriter[k] = constructFilteredBeanWriter(localBeanPropertyWriter, arrayOfClass); } } if ((bool) && (j == 0)) return; paramBeanSerializerBuilder.setFilteredProperties(arrayOfBeanPropertyWriter); }
public POJOPropertiesCollector collect() { this._properties.clear(); _addFields(); _addMethods(); _addCreators(); _addInjectables(); _removeUnwantedProperties(); _renameProperties(); PropertyNamingStrategy localPropertyNamingStrategy = _findNamingStrategy(); if (localPropertyNamingStrategy != null) _renameUsing(localPropertyNamingStrategy); Iterator localIterator1 = this._properties.values().iterator(); while (localIterator1.hasNext()) ((POJOPropertyBuilder)localIterator1.next()).trimByVisibility(); Iterator localIterator2 = this._properties.values().iterator(); while (localIterator2.hasNext()) ((POJOPropertyBuilder)localIterator2.next()).mergeAnnotations(this._forSerialization); if (this._config.isEnabled(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME)) _renameWithWrappers(); _sortProperties(); return this; }
@Test public void testBooleanSetters() { this.factory.setAutoDetectFields(false); this.factory.setAutoDetectGettersSetters(false); this.factory.setFailOnEmptyBeans(false); this.factory.setIndentOutput(true); this.factory.afterPropertiesSet(); ObjectMapper objectMapper = this.factory.getObject(); assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS)); assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT)); }
@Test public void checkResendBuildActionJsonSerialization(){ final ResendBuildAction resendBuildAction = new ResendBuildAction(GrapesNotification.NotificationType.POST_MODULE, new FilePath(new File("test")), "moduleName", "moduleVersion"); Exception execution = null; try{ final String serializedAction = JsonUtils.serialize(resendBuildAction); final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS); final ResendBuildAction newResendBuildAction = mapper.readValue(serializedAction,ResendBuildAction.class); assertEquals(resendBuildAction, newResendBuildAction); }catch (Exception e){ execution = e; } assertNull(execution); }