static { // Create a custom Mongo BSON mapper MONGO_MAPPER = new ObjectMapper(); TweakedMongoJackModule.configure(MONGO_MAPPER); // Don't include null props or empty lists MONGO_MAPPER.setSerializationInclusion(Include.NON_EMPTY); // Only include whitelisted props MONGO_MAPPER.setVisibilityChecker( MONGO_MAPPER .getSerializationConfig() .getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.NONE) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.NONE) .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)); JSON_MAPPER = new ObjectMapper(); JSON_MAPPER.setSerializationInclusion(Include.NON_EMPTY); JSON_MAPPER.setVisibilityChecker( JSON_MAPPER .getSerializationConfig() .getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.NONE) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.NONE) .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)); JSON_MAPPER.registerModule(new JsonModule()); }
// [Issue#28]: ObjectMapper.copy() public void testCopy() throws Exception { ObjectMapper m = new ObjectMapper(); assertTrue(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); assertFalse(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); InjectableValues inj = new InjectableValues.Std(); m.setInjectableValues(inj); assertFalse(m.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); m.enable(JsonParser.Feature.ALLOW_COMMENTS); assertTrue(m.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); // // First: verify that handling of features is decoupled: ObjectMapper m2 = m.copy(); assertFalse(m2.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); m2.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); assertTrue(m2.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); assertSame(inj, m2.getInjectableValues()); // but should NOT change the original assertFalse(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); // nor vice versa: assertFalse(m.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); assertFalse(m2.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); m.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); assertTrue(m.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); assertFalse(m2.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); // // Also, underlying JsonFactory instances should be distinct assertNotSame(m.getFactory(), m2.getFactory()); // [Issue#122]: Need to ensure mix-ins are not shared assertEquals(0, m.getSerializationConfig().mixInCount()); assertEquals(0, m2.getSerializationConfig().mixInCount()); assertEquals(0, m.getDeserializationConfig().mixInCount()); assertEquals(0, m2.getDeserializationConfig().mixInCount()); m.addMixIn(String.class, Integer.class); assertEquals(1, m.getSerializationConfig().mixInCount()); assertEquals(0, m2.getSerializationConfig().mixInCount()); assertEquals(1, m.getDeserializationConfig().mixInCount()); assertEquals(0, m2.getDeserializationConfig().mixInCount()); // [Issue#913]: Ensure JsonFactory Features copied assertTrue(m2.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); }
// [#438]: Support @JsonProperty.index public void testPropertyIndex() throws Exception { BeanDescription beanDesc = mapper.getDeserializationConfig().introspect(mapper.constructType(PropDescBean.class)); _verifyProperty(beanDesc, false, true); beanDesc = mapper.getSerializationConfig().introspect(mapper.constructType(PropDescBean.class)); _verifyProperty(beanDesc, false, true); }
// [#269]: Support new @JsonPropertyDescription public void testPropertyDesc() throws Exception { // start via deser BeanDescription beanDesc = mapper.getDeserializationConfig().introspect(mapper.constructType(PropDescBean.class)); _verifyProperty(beanDesc, true, false); // and then via ser: beanDesc = mapper.getSerializationConfig().introspect(mapper.constructType(PropDescBean.class)); _verifyProperty(beanDesc, true, false); }
{ mapper.setVisibilityChecker( mapper .getSerializationConfig() .getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.NONE)); }
// for [JACKSON-701] public void testInnerClassWithAnnotationsInCreator() throws Exception { BasicBeanDescription beanDesc; // first with serialization beanDesc = mapper.getSerializationConfig().introspect(mapper.constructType(Issue701Bean.class)); assertNotNull(beanDesc); // then with deserialization beanDesc = mapper.getDeserializationConfig().introspect(mapper.constructType(Issue701Bean.class)); assertNotNull(beanDesc); }
protected POJOPropertiesCollector collector( ObjectMapper m0, Class<?> cls, boolean forSerialization) { BasicClassIntrospector bci = new BasicClassIntrospector(); // no real difference between serialization, deserialization, at least here if (forSerialization) { return bci.collectProperties( m0.getSerializationConfig(), m0.constructType(cls), null, true, "set"); } return bci.collectProperties( m0.getDeserializationConfig(), m0.constructType(cls), null, false, "set"); }
@Test public void testGetAllAnalyticsLogs() throws Exception { mapper.setConfig(mapper.getSerializationConfig().withView(View.Meta.class)); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); String value = mapper.writeValueAsString(testData); when(service.findAll(null, null)).thenReturn(testData); restUserMockMvc .perform(get("/client/analytics/logs").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(value)); }
// Test to ensure that we can check property ordering defaults... public void testConfigForPropertySorting() throws Exception { ObjectMapper m = new ObjectMapper(); // sort-alphabetically is disabled by default: assertFalse(m.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)); SerializationConfig sc = m.getSerializationConfig(); assertFalse(sc.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)); assertFalse(sc.shouldSortPropertiesAlphabetically()); DeserializationConfig dc = m.getDeserializationConfig(); assertFalse(dc.shouldSortPropertiesAlphabetically()); // but when enabled, should be visible: m.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); sc = m.getSerializationConfig(); assertTrue(sc.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)); assertTrue(sc.shouldSortPropertiesAlphabetically()); dc = m.getDeserializationConfig(); // and not just via SerializationConfig, but also via DeserializationConfig assertTrue(dc.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)); assertTrue(dc.shouldSortPropertiesAlphabetically()); }
@SuppressWarnings("hiding") public void testJackson703() throws Exception { // note: need a separate mapper, need to reconfigure ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.USE_ANNOTATIONS, false); BasicBeanDescription beanDesc = mapper.getSerializationConfig().introspect(mapper.constructType(Jackson703.class)); assertNotNull(beanDesc); Jackson703 bean = new Jackson703(); String json = mapper.writeValueAsString(bean); assertNotNull(json); }
@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)); assertTrue( objectMapper.getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.ALWAYS); }
public JacksonJaxbJsonProvider buildJacksonJaxbJsonProvider() { ObjectMapper mapper = new ObjectMapper(); // mapper.enable(SerializationFeature.INDENT_OUTPUT); AnnotationIntrospector pair = AnnotationIntrospector.pair( new PrioritizeJSONPropertyJaxbAnnotationIntrospector(), new JacksonAnnotationIntrospector()); mapper.getDeserializationConfig().with(pair); mapper.getSerializationConfig().with(pair); mapper.setAnnotationIntrospectors(pair, pair); // create JsonProvider to provide custom ObjectMapper ResteasyJackson2Provider provider = new ResteasyJackson2Provider(); provider.setMapper(mapper); return provider; }
public void testAnnotationIntrospectorCopyin() { ObjectMapper m = new ObjectMapper(); m.setAnnotationIntrospector(new MyAnnotationIntrospector()); assertEquals( MyAnnotationIntrospector.class, m.getDeserializationConfig().getAnnotationIntrospector().getClass()); ObjectMapper m2 = m.copy(); assertEquals( MyAnnotationIntrospector.class, m2.getDeserializationConfig().getAnnotationIntrospector().getClass()); assertEquals( MyAnnotationIntrospector.class, m2.getSerializationConfig().getAnnotationIntrospector().getClass()); }
@Override public String nameForSerialization(final BeanPropertyDefinition beanProperty) { SerializationConfig serializationConfig = objectMapper.getSerializationConfig(); Optional<PropertyNamingStrategy> namingStrategy = Optional.fromNullable(serializationConfig.getPropertyNamingStrategy()); String newName = namingStrategy .transform(overTheWireName(beanProperty, serializationConfig)) .or(beanProperty.getName()); LOG.debug("Name '{}' renamed to '{}'", beanProperty.getName(), newName); return newName; }
@Test public void testAddAnalyticsLogs() throws Exception { mapper.setConfig(mapper.getSerializationConfig().withView(View.Meta.class)); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); AnalyticsLog log = testData.get(0); String value = mapper.writeValueAsString(log); when(service.save((AnalyticsLog) anyObject(), (UUID) anyObject())).thenReturn(log); restUserMockMvc .perform( post("/client/analytics/logs/" + app.getApplicationKey().toString()) .content(value) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().string(value)); }
@Test public void testGetAllAnalyticsLogsWithRange() throws Exception { mapper.setConfig(mapper.getSerializationConfig().withView(View.Meta.class)); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); List<AnalyticsLog> sTestData = new ArrayList<AnalyticsLog>(); sTestData.add(testData.get(1)); String value = mapper.writeValueAsString(sTestData); DateTime from = new DateTime().minusDays(10); DateTime to = new DateTime().minusDays(3); when(service.findAll(from, to)).thenReturn(sTestData); DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); String requestString = "/client/analytics/logs?from=" + from.toString(formatter) + "&to=" + to.toString(formatter); restUserMockMvc .perform(get(requestString).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(value)); }
public static ObjectMapper setupInjectablesInObjectMapper(ObjectMapper objectMapper) { objectMapper.registerModule( new SimpleModule("testModule").registerSubtypes(LocalLoadSpec.class)); final GuiceAnnotationIntrospector guiceIntrospector = new GuiceAnnotationIntrospector(); objectMapper.setAnnotationIntrospectors( new AnnotationIntrospectorPair( guiceIntrospector, objectMapper.getSerializationConfig().getAnnotationIntrospector()), new AnnotationIntrospectorPair( guiceIntrospector, objectMapper.getDeserializationConfig().getAnnotationIntrospector())); objectMapper.setInjectableValues( new GuiceInjectableValues( GuiceInjectors.makeStartupInjectorWithModules( ImmutableList.of( new Module() { @Override public void configure(Binder binder) { binder.bind(LocalDataSegmentPuller.class); } })))); return objectMapper; }
@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 void findId() { if (idMethod == null && idProperty == null) { SerializationConfig serializationConfig = objectMapper.getSerializationConfig(); JavaType javaType = serializationConfig.constructType(entityClass); BeanDescription beanDescription = serializationConfig.introspect(javaType); List<BeanPropertyDefinition> properties = beanDescription.findProperties(); for (BeanPropertyDefinition property : properties) { /* Constructor parameters don't work because they give us no value accessor if ( property.hasConstructorParameter() ) { AnnotatedParameter parameter = property.getConstructorParameter(); if ( parameter.getAnnotation(Id.class) != null ) { idPropertyName = property.getName(); } } */ if (property.hasField()) { Field field = property.getField().getAnnotated(); if (field.getAnnotation(Id.class) != null) { idPropertyName = property.getName(); idProperty = field; break; } } if (property.hasGetter()) { Method getter = property.getGetter().getAnnotated(); if (getter.getAnnotation(Id.class) != null) { idPropertyName = property.getName(); idMethod = getter; break; } if (property.hasSetter()) { Method setter = property.getSetter().getAnnotated(); if (setter.getAnnotation(Id.class) != null) { idPropertyName = property.getName(); idMethod = getter; break; } } } // setter only doesn't work because it gives us no value accessor } } // Jackson's introspect approach should find it, but our old approach below // gives some helpful errors if (idMethod == null && idProperty == null) { for (Method method : entityClass.getDeclaredMethods()) { if (method.isAnnotationPresent(Id.class)) { Class<?>[] parameters = method.getParameterTypes(); if (!Modifier.isPublic(method.getModifiers())) { throw new IllegalStateException( "Your method, " + method.getName() + ", annotated with com.marklogic.client.pojo.annotation.Id " + " must be public"); } if (parameters == null || parameters.length == 0) { Matcher matcher = getterPattern.matcher(method.getName()); if (matcher.matches()) { idPropertyName = matcher.group(2).toLowerCase() + matcher.group(3); idMethod = method; break; } else { throw new IllegalStateException( "Your no-args method, " + method.getName() + ", annotated with com.marklogic.client.pojo.annotation.Id " + " must be a proper getter method and begin with \"get\" or \"is\""); } } else { Matcher getterMatcher = getterPattern.matcher(method.getName()); if (getterMatcher.matches()) { throw new IllegalStateException( "Your getter method, " + method.getName() + ", annotated with com.marklogic.client.pojo.annotation.Id " + " must not require any arguments"); } else if (method.getName().startsWith("set")) { throw new MarkLogicInternalException( "Your setter method, " + method.getName() + ", annotated with com.marklogic.client.pojo.annotation.Id " + "was not found by Jackson for some reason. Please report this to " + "MarkLogic support."); } else { throw new IllegalStateException( "Your setter method, " + method.getName() + ", annotated with com.marklogic.client.pojo.annotation.Id " + " must be a proper setter method (beginning with \"set\")"); } } } } if (idMethod == null) { for (Field field : entityClass.getDeclaredFields()) { if (field.isAnnotationPresent(Id.class)) { if (!Modifier.isPublic(field.getModifiers())) { throw new IllegalStateException( "Your field, " + field.getName() + ", annotated with com.marklogic.client.pojo.annotation.Id " + " must be public"); } idProperty = field; break; } } } } }
private boolean isEnabled(JsonProvider provider, SerializationFeature feature) { ObjectMapper mapper = provider.locateMapper(Object.class, MediaType.APPLICATION_JSON_TYPE); SerializationConfig sConfig = mapper.getSerializationConfig(); return sConfig.isEnabled(feature); }
@Test public void testCompleteSetup() { NopAnnotationIntrospector annotationIntrospector = NopAnnotationIntrospector.instance; ObjectMapper objectMapper = new ObjectMapper(); assertTrue(this.factory.isSingleton()); assertEquals(ObjectMapper.class, this.factory.getObjectType()); Map<Class<?>, JsonDeserializer<?>> deserializers = new HashMap<Class<?>, JsonDeserializer<?>>(); deserializers.put(Date.class, new DateDeserializer()); factory.setObjectMapper(objectMapper); JsonSerializer serializer1 = new ClassSerializer(); JsonSerializer serializer2 = new NumberSerializer(); factory.setSerializers(serializer1); factory.setSerializersByType( Collections.<Class<?>, JsonSerializer<?>>singletonMap(Boolean.class, serializer2)); factory.setDeserializersByType(deserializers); factory.setAnnotationIntrospector(annotationIntrospector); this.factory.setFeaturesToEnable( SerializationFeature.FAIL_ON_EMPTY_BEANS, DeserializationFeature.UNWRAP_ROOT_VALUE, JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS); this.factory.setFeaturesToDisable( MapperFeature.AUTO_DETECT_GETTERS, MapperFeature.AUTO_DETECT_FIELDS, JsonParser.Feature.AUTO_CLOSE_SOURCE, JsonGenerator.Feature.QUOTE_FIELD_NAMES); assertFalse(getSerializerFactoryConfig(objectMapper).hasSerializers()); assertFalse(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); this.factory.setSerializationInclusion(JsonInclude.Include.NON_NULL); this.factory.afterPropertiesSet(); assertTrue(objectMapper == this.factory.getObject()); assertTrue(getSerializerFactoryConfig(objectMapper).hasSerializers()); assertTrue(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); assertTrue( serializers.findSerializer(null, SimpleType.construct(Class.class), null) == serializer1); assertTrue( serializers.findSerializer(null, SimpleType.construct(Boolean.class), null) == serializer2); assertNull(serializers.findSerializer(null, SimpleType.construct(Number.class), null)); assertTrue( annotationIntrospector == objectMapper.getSerializationConfig().getAnnotationIntrospector()); assertTrue( annotationIntrospector == objectMapper.getDeserializationConfig().getAnnotationIntrospector()); assertTrue( objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); assertTrue( objectMapper .getDeserializationConfig() .isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); assertTrue( objectMapper .getFactory() .isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)); assertTrue(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)); assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); assertFalse( objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); assertFalse(objectMapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); assertFalse(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)); assertTrue( objectMapper.getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.NON_NULL); }