com.fasterxml.jackson.databind.ser.BeanSerializerModifier Java Examples

The following examples show how to use com.fasterxml.jackson.databind.ser.BeanSerializerModifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AdditionalPropertiesSerializer.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            for (Class<?> c : TypeToken.of(beanDesc.getBeanClass()).getTypes().classes().rawTypes()) {
                if (c.isAssignableFrom(Object.class)) {
                    continue;
                }
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    if ("additionalProperties".equalsIgnoreCase(field.getName())) {
                        JsonProperty property = field.getAnnotation(JsonProperty.class);
                        if (property != null && property.value().isEmpty()) {
                            return new AdditionalPropertiesSerializer(beanDesc.getBeanClass(), serializer, mapper);
                        }
                    }
                }
            }
            return serializer;
        }
    });
    return module;
}
 
Example #2
Source File: JacksonDynamicIgnoreUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Before
public void setUp() {
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.registerModule(new SimpleModule() {
        @Override
        public void setupModule(final SetupContext context) {
            super.setupModule(context);
            context.addBeanSerializerModifier(new BeanSerializerModifier() {
                @Override
                public JsonSerializer<?> modifySerializer(final SerializationConfig config, final BeanDescription beanDesc, final JsonSerializer<?> serializer) {
                    if (Hidable.class.isAssignableFrom(beanDesc.getBeanClass())) {
                        return new HidableSerializer((JsonSerializer<Object>) serializer);
                    }
                    return serializer;
                }
            });
        }
    });
}
 
Example #3
Source File: RestTemplateTransportClientFactory.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
public static BeanSerializerModifier createJsonSerializerModifier() { // final
	// KeyFormatter
	// keyFormatter,
	// final
	// boolean
	// compactMode)
	// {
	return new BeanSerializerModifier() {
		@Override
		public JsonSerializer<?> modifySerializer(SerializationConfig config,
				BeanDescription beanDesc, JsonSerializer<?> serializer) {
			/*
			 * if (beanDesc.getBeanClass().isAssignableFrom(Applications.class)) {
			 * return new ApplicationsJsonBeanSerializer((BeanSerializerBase)
			 * serializer, keyFormatter); }
			 */
			if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) {
				return new InstanceInfoJsonBeanSerializer(
						(BeanSerializerBase) serializer, false);
			}
			return serializer;
		}
	};
}
 
Example #4
Source File: CoreAppConfig.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #5
Source File: JacksonClientModule.java    From bowman with Apache License 2.0 6 votes vote down vote up
public JacksonClientModule() {
	setSerializerModifier(new BeanSerializerModifier() {

		@Override
		public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
				List<BeanPropertyWriter> beanProperties) {
			
			for (BeanPropertyWriter writer : beanProperties) {
				if (writer.getAnnotation(LinkedResource.class) != null) {
					writer.assignSerializer(new LinkedResourceUriSerializer());
				}
			}
			
			return beanProperties;
		}
	});
	
	setMixInAnnotation(EntityModel.class, ResourceMixin.class);
	setMixInAnnotation(MethodHandler.class, MethodHandlerMixin.class);
}
 
Example #6
Source File: EntityImpl.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public void setupModule(SetupContext setupContext) {
    super.setupModule(setupContext);
    setupContext.addBeanSerializerModifier(new BeanSerializerModifier() {
        @SuppressWarnings("unchecked")
        @Override
        public JsonSerializer<?> modifySerializer(
            SerializationConfig serializationConfig,
            BeanDescription beanDescription,
            JsonSerializer<?> jsonSerializer) {
            Class<?> beanClass = beanDescription.getBeanClass();
            if (Cause.class.isAssignableFrom(beanClass)) {
                return new CauseSerializer((JsonSerializer<Object>) jsonSerializer);
            } else if (StackTraceElement.class.isAssignableFrom(beanClass)) {
                return new StackTraceElementSerializer();
            }
            return jsonSerializer;
        }
    });
}
 
Example #7
Source File: CustomFieldModule.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void setupModule(Module.SetupContext context) {
	super.setupModule(context);

	context.addBeanSerializerModifier(new BeanSerializerModifier() {

		@Override
		public JsonSerializer<?> modifySerializer(
			SerializationConfig config,
			BeanDescription beanDesc,
			JsonSerializer<?> serializer) {
			if (serializer instanceof BeanSerializerBase) {
				return new ExtraFieldSerializer(
					(BeanSerializerBase) serializer);
			}
			return serializer;

		}
	});
}
 
Example #8
Source File: AdditionalPropertiesSerializer.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            for (Class<?> c : TypeToken.of(beanDesc.getBeanClass()).getTypes().classes().rawTypes()) {
                if (c.isAssignableFrom(Object.class)) {
                    continue;
                }
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    if ("additionalProperties".equalsIgnoreCase(field.getName())) {
                        JsonProperty property = field.getAnnotation(JsonProperty.class);
                        if (property != null && property.value().isEmpty()) {
                            return new AdditionalPropertiesSerializer(beanDesc.getBeanClass(), serializer, mapper);
                        }
                    }
                }
            }
            return serializer;
        }
    });
    return module;
}
 
Example #9
Source File: FlatteningSerializer.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            if (BeanSerializer.class.isAssignableFrom(serializer.getClass())) {
                return new FlatteningSerializer(beanDesc.getBeanClass(), serializer, mapper);
            }
            return serializer;
        }
    });
    return module;
}
 
Example #10
Source File: FlatteningSerializer.java    From botbuilder-java with MIT License 5 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            if (BeanSerializer.class.isAssignableFrom(serializer.getClass())) {
                return new FlatteningSerializer(beanDesc.getBeanClass(), serializer, mapper);
            }
            return serializer;
        }
    });
    return module;
}
 
Example #11
Source File: LazyJsonModule.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void setupModule(SetupContext context) {
    // Modify the Map serializer to the delegate if it matches Map<String, ?>
    context.addBeanSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifyMapSerializer(SerializationConfig config, MapType valueType, BeanDescription beanDesc,
                                                     JsonSerializer<?> serializer) {
            if (valueType.getKeyType().equals(SimpleType.construct(String.class))) {
                return new DelegatingMapSerializer(serializer);
            }
            return serializer;
        }
    });
}
 
Example #12
Source File: DecryptingObjectMapper.java    From halyard with Apache License 2.0 5 votes vote down vote up
public DecryptingObjectMapper(
    SecretSessionManager secretSessionManager,
    Profile profile,
    Path decryptedOutputDirectory,
    boolean decryptAllSecrets) {
  super();
  this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
  this.setSerializationInclusion(JsonInclude.Include.NON_NULL);

  this.secretSessionManager = secretSessionManager;
  this.profile = profile;
  this.decryptedOutputDirectory = decryptedOutputDirectory;
  this.decryptAllSecrets = decryptAllSecrets;

  SimpleModule module = new SimpleModule();
  module.setSerializerModifier(
      new BeanSerializerModifier() {

        @Override
        public List<BeanPropertyWriter> changeProperties(
            SerializationConfig config,
            BeanDescription beanDesc,
            List<BeanPropertyWriter> beanProperties) {
          for (BeanPropertyWriter bpw : beanProperties) {
            Secret secret = bpw.getAnnotation(Secret.class);
            if (secret != null && (decryptAllSecrets || secret.alwaysDecrypt())) {
              bpw.assignSerializer(getSecretSerializer());
            }
            SecretFile secretFile = bpw.getAnnotation(SecretFile.class);
            if (secretFile != null) {
              boolean shouldDecrypt = (decryptAllSecrets || secretFile.alwaysDecrypt());
              bpw.assignSerializer(getSecretFileSerializer(bpw, secretFile, shouldDecrypt));
            }
          }
          return beanProperties;
        }
      });
  this.registerModule(module);
}
 
Example #13
Source File: WebClientTransportClientFactory.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Deprecated // reduce visibility in future release
public static BeanSerializerModifier createJsonSerializerModifier() {
	return new BeanSerializerModifier() {
		@Override
		public JsonSerializer<?> modifySerializer(SerializationConfig config,
				BeanDescription beanDesc, JsonSerializer<?> serializer) {
			if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) {
				return new InstanceInfoJsonBeanSerializer(
						(BeanSerializerBase) serializer, false);
			}
			return serializer;
		}
	};
}
 
Example #14
Source File: JacksonTest.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testAddExtraField() throws Exception {
	ObjectMapper mapper = new ObjectMapper();

	mapper.registerModule(new SimpleModule() {

		public void setupModule(SetupContext context) {
			super.setupModule(context);

			context.addBeanSerializerModifier(new BeanSerializerModifier() {

				public JsonSerializer<?> modifySerializer(
					SerializationConfig config,
					BeanDescription beanDesc,
					JsonSerializer<?> serializer) {
					if (serializer instanceof BeanSerializerBase) {
						return new ExtraFieldSerializer(
							(BeanSerializerBase) serializer);
					}
					return serializer;

				}
			});
		}
	});

	mapper.writeValue(System.out, Lists.newArrayList(new MyClass1(), new MyClass2()));
	//prints {"classField":"classFieldValue","extraField":"extraFieldValue"}
}
 
Example #15
Source File: SimpleModule.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @since 2.2
 */
public SimpleModule setSerializerModifier(BeanSerializerModifier mod) {
    _serializerModifier = mod;
    return this;
}
 
Example #16
Source File: DefaultJsonService.java    From imagej-server with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs and initializes a JsonService with an {@link ObjectService}.
 * 
 * @param objectService
 */
public DefaultJsonService(final ObjectService objectService) {

	idToObjDeserializer = new UntypedObjectDeserializer(null, null) {

		@Override
		public Object deserialize(JsonParser p, DeserializationContext ctxt)
			throws IOException, JsonProcessingException
		{
			final Object obj = super.deserialize(p, ctxt);
			if (!(obj instanceof String && ((String) obj).startsWith("object:")))
				return obj;
			final String id = (String) obj;
			if (!objectService.contains(id)) {
				throw new JsonMappingException(p, "Object does not exist");
			}
			final ObjectInfo info = objectService.find(id);
			info.updateLastUsed();
			return info.getObject();
		}
	};

	final JsonSerializer<Object> objToIdSerializer =
		new JsonSerializer<Object>()
	{

			@Override
			public void serialize(Object value, JsonGenerator gen,
				SerializerProvider serializers) throws IOException,
				JsonProcessingException
		{
				gen.writeString(objectService.register(value, "DefaultJsonService"));
			}

		};

	final SimpleModule objToIdModule = new SimpleModule();
	objToIdModule.setSerializerModifier(new BeanSerializerModifier() {

		@Override
		public JsonSerializer<?> modifySerializer(SerializationConfig config,
			BeanDescription beanDesc, JsonSerializer<?> serializer)
		{
			if (Mixins.support(beanDesc.getBeanClass())) return serializer;
			// If the serialized class is unknown (i.e. serialized using the general
			// BeanSerializer) or should not be serialized (i.e. complicated class
			// implemented interfaces such as Iterable), would be serialized as an
			// ID.
			if (serializer instanceof BeanSerializer) return objToIdSerializer;
			if (notSerialized(beanDesc.getBeanClass())) return objToIdSerializer;
			return serializer;

		}
	});
	objToIdMapper = new ObjectMapper();
	objToIdMapper.registerModule(objToIdModule);

	// register Jackson MixIns to obtain better json output format for some
	// specific types
	Mixins.registerMixIns(objToIdMapper);
}
 
Example #17
Source File: Module.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Method that module can use to register additional modifier objects to
 * customize configuration and construction of bean serializers.
 * 
 * @param mod Modifier to register
 */
public void addBeanSerializerModifier(BeanSerializerModifier mod);