下面列出了怎么用com.fasterxml.jackson.databind.ser.BeanPropertyWriter的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void processViews(SerializationConfig config, BeanSerializerBuilder builder) {
super.processViews(config, builder);
// ignore fields only for concrete class
// note, that you can avoid or change this check
Class<?> beanClass = builder.getBeanDescription().getBeanClass();
ClassUtil.ClassInfo classInfo = ClassUtil.getClassInfo(beanClass);
// if (builder.getBeanDescription().getBeanClass().equals(Entity.class))
// {
// get original writer
List<BeanPropertyWriter> originalWriters = builder.getProperties();
// create actual writers
List<BeanPropertyWriter> writers = new ArrayList<BeanPropertyWriter>();
String[] fs = this._getFilterFields(classInfo);
for (BeanPropertyWriter writer : originalWriters) {
final String propName = writer.getName();
// if it isn't ignored field, add to actual writers list
boolean find = isFilterField( classInfo, propName, fs);
if(!find){
writers.add(writer);
}
}
builder.setProperties(writers);
}
public void testSingleIntAccessorGeneration() throws Exception
{
Method method = Bean1.class.getDeclaredMethod("getX");
AnnotatedMethod annMethod = new AnnotatedMethod(null, method, null, null);
PropertyAccessorCollector coll = new PropertyAccessorCollector(Bean1.class);
BeanPropertyWriter bpw = new BeanPropertyWriter(SimpleBeanPropertyDefinition
.construct(MAPPER_CONFIG, annMethod, new PropertyName("x")),
annMethod, null,
null,
null, null, null,
false, null, null);
coll.addIntGetter(bpw);
BeanPropertyAccessor acc = coll.findAccessor(null);
Bean1 bean = new Bean1();
int value = acc.intGetter(bean, 0);
assertEquals(bean.getX(), value);
}
@Test
public void SmartErrorCodePropertyWriter_serializeAsField_still_works_for_non_Error_objects() throws Exception {
// given
final SmartErrorCodePropertyWriter secpw = new SmartErrorCodePropertyWriter(mock(BeanPropertyWriter.class));
// when
Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
secpw.serializeAsField(new Object(), mock(JsonGenerator.class), mock(SerializerProvider.class));
}
});
// then
// We expect a NPE because mocking a base BeanPropertyWriter is incredibly difficult and not worth the effort.
assertThat(ex).isInstanceOf(NullPointerException.class);
}
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);
}
protected StdScalarSerializer<Object> getSecretFileSerializer(
BeanPropertyWriter beanPropertyWriter, SecretFile annotation, boolean shouldDecrypt) {
return new StdScalarSerializer<Object>(String.class, false) {
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider provider)
throws IOException {
if (value != null) {
String sValue = value.toString();
if (!EncryptedSecret.isEncryptedSecret(sValue) && !isURL(sValue)) {
// metadataUrl is either a URL or a filepath, so only add prefix if it's a path
sValue = annotation.prefix() + sValue;
}
if (EncryptedSecret.isEncryptedSecret(sValue) && shouldDecrypt) {
// Decrypt the content of the file and store on the profile under a random
// generated file name
String name = newRandomFilePath(beanPropertyWriter.getName());
byte[] bytes = secretSessionManager.decryptAsBytes(sValue);
profile.getDecryptedFiles().put(name, bytes);
sValue = annotation.prefix() + getCompleteFilePath(name);
}
gen.writeString(sValue);
}
}
};
}
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
for (BeanPropertyWriter beanProperty : beanProperties) {
StoredAsJson storedAsJson = beanProperty.getAnnotation(StoredAsJson.class);
if (storedAsJson != null && !StoredAsJson.NULL.equals(storedAsJson.empty())) {
final JsonSerializer<Object> nullSerializer;
if (storedAsJson.binary()) {
nullSerializer = new ConstantBinarySerializer(storedAsJson.empty());
} else {
nullSerializer = new ConstantSerializer(storedAsJson.empty());
}
beanProperty.assignNullSerializer(nullSerializer);
}
}
return super.changeProperties(config, beanDesc, beanProperties);
}
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
BeanDescription beanDesc,
List<BeanPropertyWriter> beanProperties) {
if (!Registration.class.isAssignableFrom(beanDesc.getBeanClass())) {
return beanProperties;
}
beanProperties.stream()
.filter(beanProperty -> "metadata".equals(beanProperty.getName()))
.forEach(beanProperty -> beanProperty.assignSerializer(metadataSerializer));
return beanProperties;
}
@Override
public List<BeanPropertyWriter> changeProperties(final SerializationConfig config, final BeanDescription beanDesc, final List<BeanPropertyWriter> beanProperties) {
for (int i = 0; i < beanProperties.size(); i++) {
final BeanPropertyWriter beanPropertyWriter = beanProperties.get(i);
if (beanPropertyWriter.getName() == "name") {
beanProperties.set(i, new UpperCasingWriter(beanPropertyWriter));
}
}
return beanProperties;
}
/**
* Search matches of field name in ignoreList and bean properties list
* If match is found then bean property will be removed from list
*
* @param clazz class
* @param beanProperties list of bean properties
*/
private void removeFieldsByClass(Class clazz, List<BeanPropertyWriter> beanProperties) {
List<String> ignores = filterFields.getFields(clazz);
if (!ignores.isEmpty())
if (filterFields.getFilterBehaviour() == HIDE_FIELDS) {
beanProperties.removeIf(beanProperty -> ignores.contains(beanProperty.getName()));
} else
beanProperties.removeIf(beanProperty -> !ignores.contains(beanProperty.getName()));
}
/**
* Attempt to remove bean property from bean properties list
*
* @param beanDesc bean description
* @param beanProperties list of bean properties
*/
private void removeFields(BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
/*
* Try to remove fields of specified class
*/
removeFieldsByClass(beanDesc.getType().getRawClass(), beanProperties);
/*
* Try to remove fields with not specified class
*/
removeFieldsByClass(null, beanProperties);
removeFieldsByClass(void.class, beanProperties);
}
@Override
public List<BeanPropertyWriter> changeProperties(
SerializationConfig config, BeanDescription beanDesc,
List<BeanPropertyWriter> beanProperties) {
// 循环所有的beanPropertyWriter
beanProperties.forEach(writer -> {
// 如果已经有 null 序列化处理如注解:@JsonSerialize(nullsUsing = xxx) 跳过
if (writer.hasNullSerializer()) {
return;
}
JavaType type = writer.getType();
Class<?> clazz = type.getRawClass();
if (type.isTypeOrSubTypeOf(Number.class)) {
writer.assignNullSerializer(NullJsonSerializers.NUMBER_JSON_SERIALIZER);
}else if (type.isTypeOrSubTypeOf(Boolean.class)) {
writer.assignNullSerializer(NullJsonSerializers.BOOLEAN_JSON_SERIALIZER);
} else if (type.isTypeOrSubTypeOf(Character.class)) {
writer.assignNullSerializer(NullJsonSerializers.STRING_JSON_SERIALIZER);
} else if (type.isTypeOrSubTypeOf(String.class)) {
writer.assignNullSerializer(NullJsonSerializers.STRING_JSON_SERIALIZER);
} else if (type.isArrayType() || clazz.isArray() || type.isTypeOrSubTypeOf(Collection.class)) {
writer.assignNullSerializer(NullJsonSerializers.ARRAY_JSON_SERIALIZER);
} else if (type.isTypeOrSubTypeOf(OffsetDateTime.class)) {
writer.assignNullSerializer(NullJsonSerializers.STRING_JSON_SERIALIZER);
} else if (type.isTypeOrSubTypeOf(Date.class) || type.isTypeOrSubTypeOf(TemporalAccessor.class)) {
writer.assignNullSerializer(NullJsonSerializers.STRING_JSON_SERIALIZER);
} else {
writer.assignNullSerializer(NullJsonSerializers.OBJECT_JSON_SERIALIZER);
}
});
return super.changeProperties(config, beanDesc, beanProperties);
}
private boolean hasSingleElement(SerializerProvider provider) {
final BeanPropertyWriter[] props;
if (_filteredProps != null && provider.getActiveView() != null) {
props = _filteredProps;
} else {
props = _props;
}
return props.length == 1;
}
public static BeanPropertyWriter constructViewBased(BeanPropertyWriter base, Class<?>[] viewsToIncludeIn)
{
if (viewsToIncludeIn.length == 1) {
return new SingleView(base, viewsToIncludeIn[0]);
}
return new MultiView(base, viewsToIncludeIn);
}
public BuilderAndBeanPropertiyWriters constructBeanSerializerBuilder(JavaType type) {
BeanDescription beanDesc = serializerProvider.getConfig().introspect(type);
BeanSerializerBuilder builder = new BeanSerializerBuilder(beanDesc);
BeanPropertyWriter[] properties;
try {
properties = serializerFactory.findBeanProperties(serializerProvider, beanDesc, builder).toArray(new BeanPropertyWriter[0]);
} catch (JsonMappingException e) {
throw new RuntimeException("Unexpected exception", e);
}
return new BuilderAndBeanPropertiyWriters(builder, properties);
}
private PropertyWriter filter(PropertyWriter writer) {
if (!transform) {
return writer;
}
SentinelSecure secure = writer.getAnnotation(SentinelSecure.class);
if (secure == null || secure.value() == null || secure.value().isEmpty()) {
return writer;
}
return new SensitivePropertyWriter((BeanPropertyWriter) writer, secure.value());
}
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> props)
{
for (int i = 0, len = props.size(); i < len; ++i) {
BeanPropertyWriter w = props.get(i);
if (Integer.class.isAssignableFrom(w.getType().getRawClass())) {
props.set(i, new Only2BeanPropertyWriter(w));
}
}
return props;
}
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
BeanDescription beanDesc,
List<BeanPropertyWriter> beanProperties)
{
for (int i = 0; i < beanProperties.size(); ++i) {
final BeanPropertyWriter writer = beanProperties.get(i);
if (Optional.class.isAssignableFrom(writer.getType().getRawClass())) {
beanProperties.set(i, new GuavaOptionalBeanPropertyWriter(writer));
}
}
return beanProperties;
}
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
List<BeanPropertyWriter> beanProperties) {
if (!Registration.class.isAssignableFrom(beanDesc.getBeanClass())) {
return beanProperties;
}
beanProperties.stream().filter((beanProperty) -> "metadata".equals(beanProperty.getName()))
.forEach((beanProperty) -> beanProperty.assignSerializer(metadataSerializer));
return beanProperties;
}
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);
}
public BooleanFieldPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
JsonSerializer<Object> ser) {
super(src, acc, index, ser);
if (_suppressableValue instanceof Boolean) {
_suppressableBoolean = ((Boolean)_suppressableValue).booleanValue();
_suppressableSet = true;
} else {
_suppressableBoolean = false;
_suppressableSet = false;
}
}
protected OptimizedBeanPropertyWriter(BeanPropertyWriter src,
BeanPropertyAccessor propertyAccessor, int propertyIndex,
JsonSerializer<Object> ser)
{
super(src);
this.fallbackWriter = unwrapFallbackWriter(src);
// either use the passed on serializer or the original one
_serializer = (ser != null) ? ser : src.getSerializer();
_propertyAccessor = propertyAccessor;
_propertyIndex = propertyIndex;
_fastName = src.getSerializedName();
}
public IntMethodPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
JsonSerializer<Object> ser) {
super(src, acc, index, ser);
if (_suppressableValue instanceof Integer) {
_suppressableInt = (Integer)_suppressableValue;
_suppressableIntSet = true;
} else {
_suppressableInt = 0;
_suppressableIntSet = false;
}
}
public IntFieldPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
JsonSerializer<Object> ser) {
super(src, acc, index, ser);
if (_suppressableValue instanceof Integer) {
_suppressableInt = ((Integer)_suppressableValue).intValue();
_suppressableSet = true;
} else {
_suppressableInt = 0;
_suppressableSet = false;
}
}
public LongMethodPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
JsonSerializer<Object> ser) {
super(src, acc, index, ser);
if (_suppressableValue instanceof Long) {
_suppressableLong = (Long)_suppressableValue;
_suppressableSet = true;
} else {
_suppressableLong = 0L;
_suppressableSet = false;
}
}
public LongFieldPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
JsonSerializer<Object> ser) {
super(src, acc, index, ser);
if (_suppressableValue instanceof Long) {
_suppressableLong = (Long)_suppressableValue;
_suppressableSet = true;
} else {
_suppressableLong = 0L;
_suppressableSet = false;
}
}
public BooleanMethodPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
JsonSerializer<Object> ser) {
super(src, acc, index, ser);
if (_suppressableValue instanceof Boolean) {
_suppressableBoolean = ((Boolean)_suppressableValue).booleanValue();
_suppressableSet = true;
} else {
_suppressableBoolean = false;
_suppressableSet = false;
}
}
@Override
protected boolean include(BeanPropertyWriter writer) {
return !writer.getName().startsWith("_");
}
public UnwrappingBeanPropertyWriter(BeanPropertyWriter base, NameTransformer unwrapper) {
super(base);
_nameTransformer = unwrapper;
}
protected SingleView(BeanPropertyWriter delegate, Class<?> view)
{
super(delegate);
_delegate = delegate;
_view = view;
}
protected MultiView(BeanPropertyWriter delegate, Class<?>[] views) {
super(delegate);
_delegate = delegate;
_views = views;
}